C++ - 将 glfwGetTime() 用于固定时间步长

标签 c++ loops glfw

在使用 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;
            }

最佳答案

您只需要这段代码来限制更新,但将渲染保持在尽可能高的帧。代码基于此 tutorial这很好地解释了它。我所做的只是用 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()。希望这会有所帮助。

关于C++ - 将 glfwGetTime() 用于固定时间步长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390028/

相关文章:

c++ - GLFW - 窗口需要 2 秒才能打开

java - GLFW (LWJGL) 输入 - 按住 CTRL 会阻止 CharCallback

java - 如何用按钮停止循环?

c++ - 使用 GLEW、GLFW 和 g++ 编译在 OS X 10.10 下启用 OpenGL 4.1

c++ - 如何提高多线程效率?

c++ - 无法创建表示安全或可标志的类

javascript - 如何在对象拆分后检查值是否存在,如果最后一个不存在则分配它们

Ruby:带索引的循环?

c++ - 从基于两个变量的结构 vector 中获取 min_element

c++ - 函数的未命名参数可以有默认值吗?