首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++ --对固定时间步骤使用glfwGetTime()

C++ --对固定时间步骤使用glfwGetTime()
EN

Stack Overflow用户
提问于 2013-12-05 02:04:54
回答 1查看 21.9K关注 0票数 9

在使用C++ ()在我的glfwGetTime项目中做了一些研究和调试之后,我很难为我的项目制作一个游戏循环。就时间而言,我实际上只处理了Java中的纳秒,在GLFW网站上,它声明函数以、秒、返回时间。如何使用glfwGetTime()进行固定的时间步长循环?

我现在拥有的-

代码语言:javascript
运行
复制
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;
            }

}

EN

回答 1

Stack Overflow用户

发布于 2016-12-21 22:36:36

您所需要的只是这段代码来限制更新,但将呈现保持在尽可能高的框架内。代码是基于这个教程的,这很好地解释了它。我所做的就是用GLFW和C++实现同样的原则。

代码语言:javascript
运行
复制
   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()。希望这能有所帮助。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20390028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档