我正在构建一个非常强调物理的游戏。因此,我需要游戏以非常特定的间隔运行。当前代码:
public double period = .02; //this is the run interval in seconds
//main gameLoop
public void gameLoop(){
long startTime;
long sleep;
while(running){
startTime = System.nanoTime();
Graphics2D g = s.getGraphics();
operateEntities(g);
g.dispose();
s.update();
//figure out how long it must sleep to take .02s altogether
sleep = ((int)(period*1000) - (System.nanoTime() - startTime)*100000);
try{
if(sleep > 0){
Thread.sleep(sleep);
}else{
System.err.println("Warning: program runtime exceeded period");
}
}catch(Exception ex){}
gameTime += period;
}
}
这没有按预期工作。目前,主线程正在执行而根本没有休眠,并且正在触发“警告:程序运行时间超过期限”警告。
以前我使用 System.currentTimeMillis(),但它对我的目的不够准确,所以我切换到 System.nanoTime()
增加周期实际上可以加快程序的速度,而减少它会减慢它的速度。
有简单的逻辑吗?我对 System.nanoTime() 的理解是否关闭?还是有更好的方法来运行方法操作实体,处置,并在特定的时间间隔更新?
编辑:为了记录,该程序完成时间不超过 0.02 秒。它已经过测试