在使用 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;
}
Run Code Online (Sandbox Code Playgroud)
}
您所需要的只是这段代码,用于限制更新,但将渲染保持在尽可能高的帧数。该代码基于本教程,它很好地解释了它。我所做的只是用 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;
}
}
Run Code Online (Sandbox Code Playgroud)
您应该有一个用于更新游戏逻辑的函数update()和一个用于渲染的render()函数。希望这可以帮助。