将while循环限制为以30"FPS"的速度运行使用增量变量C ++ [英] Limit while loop to run at 30 "FPS" using a delta variable C++
问题描述
我基本上需要一个while循环才能仅以30"FPS"运行. 我被告知要这样做: 在您的while循环中,创建一个deltaT,如果该deltaT小于33毫秒,请使用sleep(33-deltaT)."
I basically need a while loop to only run at 30 "FPS". I was told to do this: "Inside your while loop, make a deltaT , and if that deltaT is lesser than 33 miliseconds use sleep(33-deltaT) ."
但是我真的不太确定如何初始化增量/设置此变量的方式.我也无法从提出这个建议的人那里得到答复.
But I really wasn't quite sure how to initialize the delta/what to set this variable to. I also couldn't get a reply back from the person that suggested this.
我也不确定为什么睡眠中的值是33而不是30.
I'm also not sure why the value in sleep is 33 instead of 30.
有人知道我能做什么吗?
Does anyone know what I can do about this?
这主要是为了使游戏服务器以30FPS的速度更新玩家,但是由于我没有在服务器上进行任何渲染,因此我需要一种方法来使代码休眠以限制每秒可以运行多少次或否则会过快地处理玩家.
This is mainly for a game server to update players at 30FPS, but because I'm not doing any rendering on the server, I need a way to just have the code sleep to limit how many times it can run per second or else it will process the players too fast.
推荐答案
您基本上需要执行以下操作:
You basically need to do something like this:
int now = GetTimeInMilliseconds();
int lastFrame = GetTimeInMilliseconds();
while(running)
{
now = GetTimeInMilliseconds();
int delta = now - lastFrame;
lastFrame = now;
if(delta < 33)
{
Sleep(33 - delta);
}
//...
Update();
Draw();
}
这样,您可以计算当前帧和最后一帧之间经过的毫秒数,如果它小于33毫秒(1000/30,则一秒为1000毫秒除以30 FPS = 33.333333 ....),那么您睡眠直到33毫秒过去.具有GetTimeInMilliseconds()
和Sleep()
功能,取决于您使用的库和/或平台.
That way you calculate the amount of milliseconds passed between the current frame and last frame, and if it's smaller than 33 millisecods (1000/30, 1000 milliseconds in a second divided by 30 FPS = 33.333333....) then you sleep until 33 milliseconds has passed. Has for GetTimeInMilliseconds()
and Sleep()
function, it depends on the library that you're using and/or the platform.
这篇关于将while循环限制为以30"FPS"的速度运行使用增量变量C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!