简体   繁体   中英

Slow Down Object movement in java JOGL

Using Thread.sleep(milliseconds) would delay execution of the whole program for the specified milliseconds. My problem is how do I slow down (not delay) object movement from one container into another container in my java code (implemented using JOGL - from canvas context) , so that the movement is noticeable which otherwise happens so fast?

Here is my approach for the problem:

I use Stack to represent the amount of objects on each containers. Whenever user clicks on either of the container[source], the containers Stack is to be popped until it is empty. At the same time Stack of the destination container is to be pushed. for each iteration, the containers are redrawn containing objects represented by their corresponding Stack size.

fraction of the code relevant for this Question:

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
  }
}

or

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
    }
  }
}

I have only managed to move the objects from the source to destination one by one but the movement is too fast to be noticed by eye. How do I aproach this problem?

If I understand you correctly you want to move multiple objects visibly on the screen without this happening instantaneous.

As you have noticed Thread.sleep(time) is a bad idea as it freezes the whole application.

A way around this is to supply your update logic with the elapsed 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

}

This allows you to track the time since the last update/frame and if you use it for animation it makes the speed of the object movement independent from the executing systems spees.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM