每x毫秒更新一个对象

时间:2013-06-10 09:14:18

标签: java

我遇到了问题。要制作视频游戏,我必须实现一个名为update()的函数。

参数lastCallTime是我们最后一次调用update。

必须执行以下操作:

  1. 计算自上次调用更新以来经过的时间。

  2. 如果经过的时间超过20 [ms]而不是ifUpdate = true。

  3. 并重置每个对象的lastUpdated时间。

  4. private long lastUpdated;               //The last updated time for this object.
    
    public boolean update (long lastCallTime){
        boolean ifUpdate = false;
    
        long currentTime = System.currentTimeMillis();
        long delta = (currentTime - lastCallTime);
        if (delta >= 20){
            //Do something and
            ifUpdate = true;
            lastUpdated = 0;
        }
        return ifUpdate;
    }
    
    

    线程将调用此方法:

    @Override
    public void run(){
        long lastCallTime;
        int k = 0;
    
        lastCallTime = System.currentTimeMillis();
        while(true){
            //Do something
            boolean ifUpdate = update(lastCallTime);          
        }
    }
    

1 个答案:

答案 0 :(得分:0)

前段时间我写了类似的东西。 更新方法将以FPS速率调用(示例中为24)。因此,需要计算更新方法所消耗的时间(变量timeDiff)。此外,还检查过程是否睡眠多于或少于指示(变量overSleepTime),并且此时间将在下一个循环中添加/减去。

我希望它可以帮到你

long timeDiff, sleepTime;
long afterTime, beforeTime;
long overSleepTime = 0L;

int fps = 24; // the desire FPS
long period = 1000000000L / fps;

while(true) {
  beforeTime = System.nanoTime();

  // your game logic
  update();

  afterTime = System.nanoTime();

  // timeDiff is time needed by the update process
  timeDiff = afterTime - beforeTime;
  sleepTime = (period - timeDiff) - overSleepTime;

  if(sleepTime > 0) {
    try {
      Thread.sleep(sleepTime / 1000000L); // sleeptTime is in nano secs and sleep expects millis
    } catch(InterruptedException e) {}

    // checks if the thread has slept more than desired
    overSleepTime = (System.nanoTime() - afterTime) - sleepTime;

  } else {
    // negative sleeptTime means that the system can't be update at the desired rate
    overSleepTime = 0L;
  }
}

}