loops – C++ – using glfwGetTime() for a fixed time step

loops – C++ – using glfwGetTime() for a fixed time step

All you need is this code for limiting updates, but keeping the rendering at highest possible frames. The code is based on this tutorial which explains it very well. All I did was to implement the same principle with GLFW and C++.

   static double limitFPS = 1.0 / 60.0;

    double lastTime = glfwGetTime(), timer = lastTime;
    double deltaTime = 0, nowTime = 0;
    int frames = 0 , updates = 0;

    // - While window is alive
    while (!window.closed()) {

        // - Measure time
        nowTime = glfwGetTime();
        deltaTime += (nowTime - lastTime) / limitFPS;
        lastTime = nowTime;

        // - Only update at 60 frames / s
        while (deltaTime >= 1.0){
            update();   // - Update function
            updates++;
            deltaTime--;
        }
        // - Render at maximum possible frames
        render(); // - Render function
        frames++;

        // - Reset after one second
        if (glfwGetTime() - timer > 1.0) {
            timer ++;
            std::cout << FPS:  << frames <<  Updates: << updates << std::endl;
            updates = 0, frames = 0;
        }

    }

You should have a function update() for updating game logic and a render() for rendering. Hope this helps.

loops – C++ – using glfwGetTime() for a fixed time step

Leave a Reply

Your email address will not be published.