I am creating a program that has two balls which produce a sound when bouncing off the walls and each other. I am having trouble when they collide with each other, as my value for when they hit each other does not seem to be working. Here is my source code :
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.applet.AudioClip;
import java.awt.event. *;
public class BallBouncing extends Applet implements Runnable {
int x_pos = 20;
int y_pos = 100;
int x_speed = 1;
int y_speed = 1;
int x1_pos = 70;
int y1_pos = 130;
int x1_speed = 1;
int y1_speed = 1;
int appletsize_x = 300;
int appletsize_y = 200;
int radius = 20;
int pos = (x_pos - x1_pos)*(x_pos - x1_pos) + (y_pos - y1_pos)*(y_pos - y1_pos);
double pos1 = Math.sqrt(pos);
public AudioClip sound1, sound2;
Thread t;
Button b1 = new Button("Reverse Direction");
public void init() {
b1.addActionListener(new B1());
add(b1);
}
class B1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
x_speed = +3;
y_speed = -3;
}
}
public void start() {
t = new Thread(this);
t.start();
}
public void stop() {
}
public void paint(Graphics g) {
g.setColor (Color.blue);
g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
g.fillOval(x1_pos - radius, y1_pos - radius, 2 * radius, 2 * radius);
}
public void run() {
sound1 = getAudioClip( getDocumentBase(), "Audio1.au" );
sound2 = getAudioClip( getDocumentBase(), "Audio2.au" );
while (true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {}
if (x_pos > appletsize_x - radius)
{
x_speed = -3;
sound2.play();
}
else if (x_pos < radius)
{
x_speed = +3;
sound2.play();
}
else if (y_pos > appletsize_y - radius)
{
y_speed = -3;
sound2.play();
}
else if (y_pos < radius)
{
y_speed = +3;
sound2.play();
}
else if (x1_pos > appletsize_x - radius)
{
x1_speed = -3;
sound2.play();
}
else if (x1_pos < radius)
{
x1_speed = +3;
sound2.play();
}
else if (y1_pos > appletsize_y - radius)
{
y1_speed = -3;
sound2.play();
}
else if (y1_pos < radius)
{
y1_speed = +3;
sound2.play();
}
else if (pos1 < 40)
{
x_speed = -3;
x1_speed = +3;
y_speed = -3;
y1_speed = +3;
sound1.play();
}
x_pos += x_speed;
y_pos += y_speed;
x1_pos += x1_speed;
y1_pos += y1_speed;
repaint();
}
}
}
Any help would be appreciated, thanks.