9

After doing some research and debugging in my C++ project with glfwGetTime(), I'm having trouble making a game loop for my project. As far as time goes I really only worked with nanoseconds in Java and on the GLFW website it states that the function returns the time in seconds. How would I make a fixed time step loop with glfwGetTime()?

What I have now -

while(!glfwWindowShouldClose(window))
    {
            double now = glfwGetTime();
            double delta = now - lastTime;
            lastTime = now;

            accumulator += delta;

            while(accumulator >= OPTIMAL_TIME) // OPTIMAL_TIME = 1 / 60
            {
                     //tick

                    accumulator -= OPTIMAL_TIME;
            }

}

tcoy
  • 179
  • 1
  • 3
  • 11

1 Answers1

9

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.

onurhb
  • 1,151
  • 2
  • 15
  • 31