我正在编写一个游戏循环,我在下面的示例中找到了代码here http://www.java-gaming.org/index.php?topic=24220.0。我还研究了其他进行游戏循环的方法,例如本文 https://dewitters.com/dewitters-gameloop/。但我无法让其中任何一个工作。所以我保留了第一个链接中的那个。
我想知道的是:
- Is the way I wrote my game loop a good way to do this?
- 我应该使用
Thread.sleep();
在我的游戏循环中?
这是我当前的代码:
public void run(){
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
long lastFpsTime = 0;
while(true){
long now = System.nanoTime();
long updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ((double)OPTIMAL_TIME);
lastFpsTime += updateLength;
if(lastFpsTime >= 1000000000){
lastFpsTime = 0;
}
this.updateGame(delta);
this.repaint();
try{
Room.gameTime = (lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000;
System.out.println(Room.gameTime);
Thread.sleep(Room.gameTime);
}catch(Exception e){
}
}
最终你会想要搬到类似的地方LWJGL http://www.lwjgl.org/,但让我强调一下,继续做你现在在这里做的事情。它将教您基础知识。
你的循环做得很好。看起来不错,给点建议:
重绘不会立即渲染屏幕。它告诉重绘管理器 http://docs.oracle.com/javase/6/docs/api/javax/swing/RepaintManager.html准备好后进行渲染。使用invalidate立即涂漆 http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#paintImmediately%28int,%20int,%20int,%20int%29反而。paintImmediately
将阻止执行,直到组件被重新绘制,以便您可以测量渲染时间。
Thread.sleep
通常有几毫秒的漂移。您应该使用它来防止循环使用过多的 CPU,但请确保您了解如果您休眠 10 毫秒,您可能会休眠 5 毫秒,或者您可能会休眠 20 毫秒。
-
Lastly:
double delta = updateLength / ((double)OPTIMAL_TIME);
If updateLength
小于OPTIMAL_TIME,不调用update。换句话说,如果 delta 小于 1,则不更新。本教程 http://gafferongames.com/game-physics/fix-your-timestep/比我以前更好地解释了为什么。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)