You are here:

Java/Java applet for bouncing balls

Advertisement


Question
Hi I have created an applet for an assignment that has bouncing balls within a frame. However I need these to now bounce of each other, or collide if you will. However I am not able to do this!

Any help appreciated!!

Original code below  WARNING applet flickers, cant get it to stop so if you have epilepsy dont open it!



import java.awt.*;
import java.awt.image.ImageObserver;
import java.util.*;



  class Ball{
       protected int radius = 20;
       protected int x, y;
       protected int dx = 2, dy = 4;
       protected int width, height;
       protected Image image;
       public final Random generator = new Random();
       Color bColour;
       public static int delay = 100;
       Graphics g;
     
       
       
       public Ball(Color c, int width, int height){
      int max = width - radius;
      int maxh = height - radius;
      int min = 0 + radius;
      
      x = (int) ( min + (Math.random() * (max - min)));
      y = (int) ( min + (Math.random() * (maxh - min)));
      
    double w = Math.random();
      
      if (w >= .5)
      {
         dx = generator.nextInt(10)+4;
         dy = generator.nextInt(10)+4;
         }
      
      else {
         dx = generator.nextInt(10)+4 *-1 ;
         dy = generator.nextInt(10)+4 *-1;
      }
      
      bColour = c;
    }

       
       public void movement(int widthsc, int heightsc)
       {
         
         width = widthsc;
         height = heightsc;
         
         if (x < radius || x > width - radius) {
         dx  =  -dx;
         }
         if (y < radius || y > height - radius) {
         dy  =  -dy;
         }
         x += dx;
         y += dy;
         
       }
       
       
      
       
       public void paint(Graphics graphball ){
         
         g = graphball;
         g.setColor(bColour);
         g.fillOval(x - radius, y - radius,
         radius * 2, radius * 2);

       }
  }


public class bounceBalls
   extends java.applet.Applet implements Runnable {

protected Color color = Color.green;
 protected int numBalls;
 Ball balls[];
 private Color Colors[] = {Color.GRAY, Color.BLUE, Color.ORANGE, Color.CYAN, Color.BLACK, Color.MAGENTA, Color.GREEN, Color.PINK, Color.YELLOW, Color.RED};
 private int c; //count colours
 protected Thread bouncingThread = null;
 protected int x, y;
 protected Image image;
 protected Graphics offscreen;
 private final Random generator = new Random();
 
 
 
 public void init() {
    
  
        image = createImage(getWidth(), getHeight());
        offscreen = image.getGraphics();
        numBalls = Integer.parseInt(getParameter("balls"));
        balls = new Ball[numBalls];
    
    for (int i = 0; i< numBalls; i++)
    {
       if (c>=10)
       {
         c = generator.nextInt(9);
       }
       
       
       balls[i] = new Ball(Colors[c], getWidth(), getHeight());
       c++;
    }
    
   }
 
 
 
 public void start() {
    
    if (bouncingThread == null){
   bouncingThread = new Thread(this);
   bouncingThread.start();
    }
 }

 public void run() {
      while (true) {
         
         
        try {
         Thread.currentThread().sleep(Ball.delay);
        } catch (InterruptedException  e) {}
         for (int j =0; j< numBalls; j++)
         {
         balls[j].movement(getWidth(), getHeight());
         }
        repaint();
        
      }
      
     
    }
 
 
 
 public void paint(Graphics g) {
    super.paint(g);
     
      offscreen.setColor(Color.white);
        offscreen.fillRect(0,0,getWidth(), getHeight());
        
        for (int z = 0; z<numBalls; z++)
        {
         balls[z].paint(offscreen);
         g.drawImage(image,0,0, this);
        }
}





}

Answer
This is a bit more complex than bouncing off of walls as you need to determine 2 things:
1. Which balls if any are bouncing off each other?
2. What angle do they rebound at?

1. If you have a few balls (less than 20) then you can store your balls as Ellipse2D.Double. Then use the Area class to wrap each Ellipse2D.Double. Finally you can use intersect to create an intersection and determine if that intersection is empty.

2. There are various ways to emulate the physics of this, but a simple way is to exchange the velocity of the two balls. This will look a bit odd as two balls comming directly at each other, but offset, will simply rebound in the oppset direction.
E.g. (define a shape variable in the ball code that holds and updates the ball's shape.


for(int i = 0; i < balls.length; i++)
  for(int j = i + 1; j < balls.length; j++)
  {
     Area area1 = new Area(balls[i].shape);
     Area area2 = new Area(balls[j].shape);
     area1.intersect(area2);
     if(~area1.isEmpty())
     {
        int ball1Dx = ball1.dx;
        int ball1Dy = ball1.dy;
        ball1.dx = ball2.dx;
        ball1.dy = ball2.by;
        ball2.dx = ball1Dx;
        ball2.dy = ball2Dy;
     }
  }

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.