在java JOGL中减慢对象移动

时间:2015-01-19 20:56:36

标签: java jogl

使用Thread.sleep(milliseconds)会延迟整个程序执行指定的毫秒数。我的问题是如何在我的java代码中使用JOGL(从画布上下文实现)减慢(不延迟)从一个容器到另一个容器的对象移动,这样移动是明显的,否则会发生这么快?

以下是我解决问题的方法:
我使用Stack来表示每个容器上的对象数量。每当用户点击任一容器[source]时,就会弹出容器Stack,直到它为空。同时推送目标容器的Stack。对于每次迭代,重新绘制容器,其中包含由对应的Stack大小表示的对象。

与此问题相关的代码的一部分:

public void moveObjects(Container source, Container destination) {
  while (!source.stack.isEmpty()) {
    destination.stack.push(destination.stack.size() + 1);
    source.stack.pop();
    //redraw both containers with their new amount of objects represnted using their stack size
  }
}

public void moveObject(int source, int dest) {
  while (!this.container[source].stack.isEmpty()) {
    this.container[dest].stack.push(this.container[dest].stack.size() + 1);
    this.container[source].stack.pop();
    try {
      Thread.sleep(100);
    } catch (InterruptedException ie) {
      // Handle exception here
    }
  }
}

我只是设法将物体从源头逐个移动到目的地,但是移动太快而不能被眼睛注意到。我如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想在屏幕上明显地移动多个物体,而不会立即发生这种情况。

正如您所注意到的那样Thread.sleep(time)是一个坏主意,因为它会冻结整个应用程序。

解决这个问题的方法是为您的更新逻辑提供已用时间:

long lastTime = System.nanoTime();
while(running)
{
  long now = System.nanoTime();
  updateLogic(now-lastTime); //this handles your application updates
  lastTime = now;
}

void updateLogic(long delta)
{
   ...
   long movementTimespan +=delta
   if(movementTimespan >= theTimeAfterWhichObjectsMove)
   {
       //move objects here
       //...
       movementTimespan -= theTimeAfterWhichObjectsMove;
   }

   //alternatively you could calculate how far the objects have moved directly from the delta to get a smooth animation instead of a jump
   //e.g. if I want to move 300 units in 2s and delta is x I have to move y units now

}

这使您可以跟踪自上次更新/帧以来的时间,如果将其用于动画,则会使对象移动的速度与执行系统的速度无关。

相关问题