gpt4 book ai didi

java - 如何使渲染循环以一致的速率运行?

转载 作者:行者123 更新时间:2023-12-02 07:41:04 25 4
gpt4 key购买 nike

我编写了一个程序,其中基于用户输入移动动画 Sprite ,所有这些都发生在 while(true) 中。环形。到目前为止,我对循环进行计时的唯一方法是使用 sleep(20)在每次循环结束时。我注意到这会对我的 Sprite 的物理特性产生负面影响,因为我计算重力的公式是 velocity = velocity + GRAVITY * Elapsed-Time而且由于循环的运行速度不一致,重力的影响也不一致。 有没有办法让循环保持一致运行,或者有更好的方法来计时,以便它实际上按计划运行?

最佳答案

首先,确定您希望帧持续多长时间。如果您想要 30 fps,那么您将拥有

final long frameDuration = 1000 / 30;

接下来,当你开始渲染时,存储时间,就像这样

final long then = System.currentTimeMillis();
render(); // surely it's more than this but you get the idea
final long now = System.currentTimeMillis();

final long actualDuration = now - then;
final long sleepDuration = frameDuration - actualDuration;

if(sleepDuration > 0) {
sleep(sleepDuration);
} else {
throw new FrameTooLongException();
}

关于java - 如何使渲染循环以一致的速率运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com