C++ - using glfwGetTime() for a fixed time step
Asked Answered
G

1

10

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;
            }

}

Girard answered 5/12, 2013 at 2:4 Comment(4)
Keep track of the last time you did something and subtract that from the time now to get a delta. When the delta is >= the step you want, do something again.Nagaland
This is how I have it set up as of now pastebin.com/LV650dGyGirard
Better to edit the question and add the code there. External links aren't reliable.Nagaland
Oh, right, sorry about that.Girard
S
10

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.

Sextain answered 21/12, 2016 at 22:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.