smooth animation

From: Mike Crenshaw (someone_at_microsoft.com)
Date: 09/28/04


Date: Tue, 28 Sep 2004 18:06:43 +0200

Hi

I'm trying to figure out how to make an animation move smoothly.. so i've
been looking around.. i've found 3 other methods besides just using sleep()
at each frame.. i've tried implementing these methods but i cant see much of
a difference.. but which of the following, if any, is the best way to go
about it.. or is there a better way..

method 1: the nono
..
while(true){
    x++; //some simple movement
    y++;
    paint(getGraphics());
    try{
        Thread.currentThread().sleep(delay);
    }
    catch(Exception e){}
}

method 2:
...
while(true){
    long start = System.currentTimeMillis();
    x++; //some simple movement
    y++;
    paint(getGraphics());
    try {
        Thread.sleep(Math.max(0, (start + delay) -
System.currentTimeMillis()));
    }
    catch (InterruptedException e) {};
}

method 3:
...
while(true){
    long start = System.currentTimeMillis();
    x++; //some simple movement
    y++;
    paint(getGraphics());
    long sleepTime = delay - (System.currentTimeMillis() - start);
    if (sleepTime > 0)
    try{
        Thread.currentThread().sleep(sleepTime);
    }
    catch(Exception e){}
}

method 4: frame independent

int velocity = 500;
long end_time = 0;
long start_time = System.currentTimeMillis();
float elapsed_time = 0;
float dtime = 0;
while(true){
      end_time = System.currentTimeMillis();
      elapsed_time = end_time - start_time ;
      dtime = elapsed_time / 1000 ;
      x += dtime * velocity; //some simple movement
      y += dtime * velocity;
      start_time = System.currentTimeMillis();
      paint(getGraphics());
      try{
          Thread.currentThread().sleep(delay);
      }
      catch(Exception e){}
}

thanx
mike