有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java JOGL中减慢对象移动

使用Thread.sleep(milliseconds)会将整个程序的执行延迟指定的毫秒。我的问题是,在我的java代码中(使用JOGL-from canvas context实现),如何减慢(而不是延迟)对象从一个容器移动到另一个容器的速度,从而使移动变得明显,否则就会发生得如此之快

下面是我解决这个问题的方法:

我使用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) 个答案

  1. # 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
    
    }
    

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