游戏开发:如何限制FPS?
我正在编写一个游戏,我看到 FPS 算法无法正常工作(当他必须计算更多时,他会睡更长的时间......)所以,问题很简单:如何计算具有正确 FPS 的睡眠时间?
我知道以微秒为单位更新游戏一帧需要多长时间,当然还有我想要达到的 FPS。
我正在疯狂地寻找一个简单的例子,但我找不到......
代码可能是Java、C++或伪代码......
I'm writing a game, and I saw the FPS algorithm doesn't work correctly (when he have to calculate more, he sleeps longer...) So, the question is very simple: how to calculate the sleeptime for having correct FPS?
I know how long it took to update the game one frame in microseconds and of course the FPS I want to reach.
I'm searching crazy for a simple example, but I can't find one....
The code may be in Java, C++ or pseudo....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
渲染一帧应花费的时间为
1/FPS
秒(如果您的目标是 10 FPS,则应在每一帧上花费 1/10 = 0.1 秒)。因此,如果渲染需要X
秒,您应该“休眠”1/FPS - X
秒。例如,将其转换为毫秒,您会得到
如果由于某种原因花费了超过 1/FPS 来渲染帧,您将获得负睡眠时间,在这种情况下,您显然只是跳过睡眠。
The time you should spend on rendering one frame is
1/FPS
seconds (if you're aiming for, say 10 FPS, you should spend 1/10 = 0.1 seconds on each frame). So if it tookX
seconds to render, you should "sleep" for1/FPS - X
seconds.Translating that to for instance milliseconds, you get
If it, for some reason took more than
1/FPS
to render the frame, you'll get a negative sleep time in which case you obviously just skip the sleeping.每帧的微秒数为
1000000/frames_per_second
。如果您知道您已经花费了elapsed_microseconds
进行计算,那么您需要睡眠的时间为:The number of microseconds per frame is
1000000 / frames_per_second
. If you know that you've spentelapsed_microseconds
calculating, then the time that you need to sleep is:尝试...
...按照 http://www.gamedev .net/community/forums/topic.asp?topic_id=510019
Try...
... as per http://www.gamedev.net/community/forums/topic.asp?topic_id=510019
请查看这篇有关不同 FPS 处理方法的文章。
更新:使用网络档案中的此链接,因为原始网站已消失:https://web.archive.org/web/20161202094710/http://dewitters.koonsolo.com/gameloop.html
Take a look at this article about different FPS handling methods.
UPDATE: use this link from Web Archive as original website disappeared: https://web.archive.org/web/20161202094710/http://dewitters.koonsolo.com/gameloop.html