16.66ms帧时间.当sleep()仅持续整毫秒时,如何获得完美的60 fps? [英] 16.66ms frames times. How do you get a perfect 60 fps when sleep() only goes by whole milliseconds?

查看:166
本文介绍了16.66ms帧时间.当sleep()仅持续整毫秒时,如何获得完美的60 fps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢用C ++和Java制作小游戏,但总有一些困扰我,而且我从不完全了解如何解决它.

I enjoy making little games in C++ and Java, but something has always bothered me, and I've never quite understood how to remedy it.

C ++和Java中的睡眠仅以毫秒为单位.意思是如果你这样做

Sleep in C++ and Java only works in milliseconds. Meaning that if you do

startTime=clock();
-------Execute everything in that frame-----
endTime=clock(); 
sleep(x-(endTime-startTime));

如果x为16,则每秒可获得62.5帧 如果x为17,则每秒可获得58.8帧

if x is 16 you get 62.5 frames per second if x is 17 you get 58.8 frames per second

这两者都不是完美的60,无法适应显示器的刷新率.

Neither of which is that perfect 60 to fit a monitor's refresh rate.

但是我注意到有些游戏,例如Warframe会说"16.66 ms frame time"(帧时间),这意味着它们的引擎能够以某种方式以更高的精度进入睡眠状态.

But I've noticed some games like Warframe will say "16.66 ms frame time" meaning that their engine was able to somehow sleep with greater precision.

那么,如何获得完美的60分?

So how do you get that perfect 60?

最好是在C ++中,因为这是我现在正在使用的,但是回答Java也将有所帮助

Preferably in C++ as that's what i'm working with right now, but answering for Java too would also be helpful

推荐答案

仅依靠sleep是错误的:您需要以固定速率进行调度,并由纳秒精度指定.使用

Relying on sleep alone is wrong anyway: you need scheduling at a fixed rate, and specified by you at the nanosecond precision. Use

final ExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(task, 
    TimeUnit.SECONDS.toNanos(1/60), 
    TimeUnit.SECONDS.toNanos(1/60), 
    TimeUnit.NANOSECONDS);

这篇关于16.66ms帧时间.当sleep()仅持续整毫秒时,如何获得完美的60 fps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆