C++-对固定的时间步长使用glfwGetTime()

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

本文关键字:glfwGetTime 时间 C++-      更新时间:2023-10-16

在用glfwGetTime()对我的C++项目进行了一些研究和调试之后,我在为我的项目制作游戏循环时遇到了问题。就时间而言,我在Java中实际上只使用纳秒,在GLFW网站上,它声明该函数以为单位返回时间。如何使用glfwGetTime()生成固定的时间步长循环?

我现在有什么-

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

}

您只需要这段代码来限制更新,但保持渲染在尽可能高的帧上。代码基于本教程,本教程对此进行了很好的解释。我所做的只是用GLFW和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;
        }
    }

您应该有一个用于更新游戏逻辑的函数update()和一个用于渲染的函数render()。希望这能有所帮助。