我写一个游戏循环,我发现在例如下面的代码在这里。我还研究了进行游戏循环的其他方法,例如本文。但是我无法让这些工作。因此,我保留了第一个链接中的那个。
我想知道的是:
我编写游戏循环的方式是否是实现此目标的好方法? 有什么建议?
我应该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){
}
}