I need a help in BouncingBall
I have a BouncingBall program, I'm having problem to add something here.
I have a ball that bounce on the screen.I need add something that makes two ball collide with each other and bounce away from each other appropriately. Can anybody help me in that.
Here is my code;
BouncingBall Class:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BouncingBall extends JFrame
{
private int x;
private int y;
private int xv;
private int yv;
private int R;
private int G;
private int B;
private Color color;
public int xMax=400;
public int yMax=400;
public static int r = 15;
private MouseHandler mh;
public static ArrayList<Ball> ballsList;
Ball thisBall;
BouncingBall bb;
public BouncingBall()
{
super( "Click in the window to add balls" );
ballsList = new ArrayList<Ball>();
mh = new MouseHandler( );
addMouseListener( mh );
setSize( xMax, yMax );
setVisible( true );
bb = this;
}
private class MouseHandler extends MouseAdapter{
public void mouseClicked(MouseEvent me){
x = me.getX();
y = me.getY();
R = 0 + (int) (256 * Math.random());
G = 0 + (int) (256 * Math.random());
B = 0 + (int) (256 * Math.random());
color = new Color(R, G, B);
ballsList.add(thisBall = new Ball(bb, x, y, xMax, yMax, color));
repaint();
}
}
public void paint(Graphics g)
{
super.paint(g);
for (Ball b : ballsList)
{
b.setXmax(this.getWidth());
b.setYmax(this.getHeight());
b.draw(g);
repaint();
}
}
public static void main(String [] args){
BouncingBall app = new BouncingBall();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
BAll class
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ball
{
private int x;
private int y;
private int xv;
private int yv;
public int xMax=350;
public int yMax=350;
public static int r = 15;
private Color color;
BouncingBall space;
public Ball(BouncingBall spacex, int ballx, int bally,
int xMax, int yMax, Color ballcolor)
{
x = ballx;
y = bally;
int theta = (int)(Math.random() * (-2 * Math.PI));
xv = (int)(r * (Math.cos(theta)/10)) ;
yv = (int)(r * (Math.sin(theta)/8));
this.xMax = xMax;
this.yMax = yMax;
color = ballcolor;
space = spacex;
}
public void setXmax(int newXmax)
{
xMax= newXmax;
}
public void setYmax(int newYmax)
{
yMax = newYmax;
}
public void collide()
{
}
public void Bounce()
{
if (x+xv>xMax)
{
x=xMax;
xv=-xv;
}
else if (x+xv<0)
{
x=0;
xv=-xv;
}
else
x+=xv;
if (y+yv>yMax)
{
y=yMax;
yv=-yv;
}
else if (y+yv<0)
{
y=0;
yv=-yv;
}
else
y+=yv;
space.repaint();
}
public void draw(final Graphics g){
//g.setColor(g.getBackground());
g.setColor(color);
g.fillOval(x - r/2, y - r/2, r, r);
Bounce();
}
}

