在使用 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/