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

荒凉一梦 提交于 2019-12-10 17:33:31

问题


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

}


回答1:


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.



来源:https://stackoverflow.com/questions/20390028/c-using-glfwgettime-for-a-fixed-time-step

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!