Timing

True animation should provide a timing engine. This ball is rather fast on some platforms, rather slow on others. You'd like it's performance to be more uniform.

Think of a movie. It plays at 24 frames per second, and movies are shot at that frame rate. You wouldn't want the speed of a movie to be dependent on the speed of the projector, especially if different projectors had different speeds. (In fact this is exactly why old silent movies look so ridiculously speeded up. The silent movies were shot at about 15 frames per second, but modern projectors play everything at 24 frames per second. Television's even worse. It plays at 30 frames per second. HDTV is higher still.)

Although you can't speed up an animation beyond what a virtual machine is capable of playing, you can slow it down using sleep(). The following applet limits the movement of the ball to 100 pixels (both vertically and horizontally) per second.


import java.awt.*;
import java.applet.*;
import java.util.*;


public class SleepyBounce extends Applet implements Runnable {

  Rectangle r;
  int deltaX = 1;
  int deltaY = 1;
  int speed = 50;
  
  public void init () {  
    r = new Rectangle(37, 17, 20, 20);
    Thread t = new Thread(this);
    t.start();  
  }
  
  
  public void paint (Graphics g) {
    g.setColor(Color.red);
    g.fillOval(r.x, r.y, r.width, r.height);
  }

  public void run() {

    while (true) {  // infinite loop
      long t1 = (new Date()).getTime();
      r.x += deltaX;
      r.y += deltaY;
      if (r.x >= size().width || r.x < 0) deltaX *= -1;
      if (r.y >= size().height || r.y < 0) deltaY *= -1;
      this.repaint();
      long t2 = (new Date()).getTime();
      long sleepTime = speed - (t2 - t1);
      if (sleepTime > 0) {
        try {
          Thread.sleep(sleepTime);
        }
        catch (InterruptedException ie) {
        }
        
      } 
      
    }
    
  }

}

Previous | Next | Top
Last Modified December 15, 2000
Copyright 1997-2000 Elliotte Rusty Harold
elharo@metalab.unc.edu