Five Bouncing Balls

SAMPLE APPLET:

ASSIGNMENT: The collision detection algorithm used in this applet is far from perfect (as you can see by observing the behavior of the applet). BUT it is reasonably simple.

There are a few things you need to do to get this to work:

  1. Set up several arrays to keep track of the balls:
      int[] x = {5, 100, 170, 200, 280}; //starting x position
      int[] y = {5, 100, 170, 200, 280}; //starting y position
      int[] xDir = {1, 1, -1, -1, -1}; //positive one
      int[] yDir = {1, 1, -1, 1, 1}; 
      int[] xInc = {3, 2, 3, 1, 1};
      int[] yInc = {1, 2, 1, 2, 2};
      Color[] color = {Color.red, Color.blue, Color.green,
                       Color.black, Color.cyan};
    
    All this goes before the init method.
  2. Set up the random number generator:
      First: import 
        import java.util.*;
      Second: declare
        Random r;
      Third: initialize
        r = new Random();
    
  3. Set your run method up like this:
    public void run() { while(true) { for(int i=0; i<x.length; i++){ x[i]+=(xInc[i] * xDir[i]); y[i]+=(yInc[i] * yDir[i]); } repaint(); collisionCheck(); try { Thread.sleep(sleepFor); }catch(Exception e) { } } }
  4. Create the collisionCheck() method:
    public void collisionCheck(){ for(int i=0; i<x.length; i++){ if(x[i] > XMAX || x[i] < 0){ xDir[i] *= -1; xInc[i]=Math.abs(r.nextInt()%5)+1; if(x[i] > XMAX) x[i] = XMAX -2; else x[i] = 2; } else if(y[i] > YMAX || y[i] < 0){ yDir[i] *= -1; yInc[i]=Math.abs(r.nextInt()%5)+1; if(y[i] > YMAX) y[i] = YMAX -2; else y[i] = 2; } } for(int i=0; i<x.length-1; i++){ for(int a = i+1; a<x.length; a++){ if(Math.abs(x[i]-x[a]) <= 2*RADIUS && Math.abs(y[i]-y[a]) <= 2*RADIUS){ xDir[i]*=-1; xInc[i]=Math.abs(r.nextInt()%5)+1; xDir[a]*=-1; xInc[a]=Math.abs(r.nextInt()%5)+1; yDir[i]*=-1; yInc[i]=Math.abs(r.nextInt()%5)+1; yDir[a]*=-1; yInc[a]=Math.abs(r.nextInt()%5)+1; } } } }