问题描述
在使用glfwGetTime()在C ++项目中进行了一些研究和调试之后,我在为项目创建游戏循环时遇到了麻烦.就时间而言,我实际上只在Java中使用了纳秒级,并且在GLFW网站上指出该函数以 seconds 返回时间.如何使用glfwGetTime()进行固定的时间步循环?
After doing some research and debugging in my C++ project with glfwGetTime(), I'm having trouble making a game loop for my project. As far as time goes I really only worked with nanoseconds in Java and on the GLFW website it states that the function returns the time in seconds. How would I make a fixed time step loop with 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 ++实现相同的原理.
All you need is this code for limiting updates, but keeping the rendering at highest possible frames. The code is based on this tutorial which explains it very well. All I did was to implement the same principle with GLFW and 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().希望这会有所帮助.
You should have a function update() for updating game logic and a render() for rendering. Hope this helps.
这篇关于C ++-使用glfwGetTime()进行固定的时间步长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!