# Flipping the direction on the bouncing ball problem!

• 06-17-2010, 01:45 AM
ferdzz
Flipping the direction on the bouncing ball problem!
Hi all, I'm currently trying to complete the famous basic program "Bouncing Ball". For those who are not familiar with this problem. Here is the spec:

- write a swing component that extends JPanel
- contains a ball with x and y coords and with vx, vy random velocities
- constructor has a thread that updates the position of the ball
- if the ball hits any of the edges flip the sign of the velocity accordingly
- paintComponent that draws the ball at its location

I have completed most of my code but cannot seem to figure out how to make it bounce of the "walls"... The ball seems to get stuck at the top right corner and it just continuously bounces off of the corner.

Here is my code:

import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

public class BouncingBall extends JPanel
{
private double x,y;
private double vx,vy;
private static final Random rng = new Random();
private volatile boolean running = true;

public BouncingBall(){
this.setPreferredSize(new Dimension(300,300));
this.setBackground(Color.BLACK);
Random rng = new Random();
x = 135;
y = 135;

vx = rng.nextInt(3)+1;
vy = rng.nextInt(3)+1;

public void run() {
while(running) {
try { Thread.sleep(40); } catch(InterruptedException e) { }
draw();
repaint();
}
}
}).start();

}

public void draw(){
x -= vx;
y -= vy;
if (y>300 || y<0){
y = -y;
}

if (x>300 || x<0){
x = -x;
}
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fill(new Ellipse2D.Double(x, y,30,30));
}

public static void main (String[] args){
JFrame f = new JFrame("Bouncing Ball");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
f.setVisible(true);
f.pack();
}
}

Any help would be appreciated. Thanks!
• 06-17-2010, 02:02 AM
Norm
How does your algorithm control the balls movement?
If the ball is to move to the right, then you must increment the x value.
If the ball is to move to the left, then you must decrement the x value.

Hint: set the increment value to be + when moving to the right and to - when moving to the left.
x = x + incrVal; // move to next location
incrVal is +1 to go right and -1 to go left

How are you changing the values? Use println() statements to print the values after each time you change them.
• 06-17-2010, 04:06 AM
Fubarable
Duplicate post locked. OP, please do not double post questions.
• 06-17-2010, 04:12 AM
ferdzz
My mistake, i just figured i put it under the wrong category
• 06-17-2010, 04:23 AM
Fubarable
Quote:

Originally Posted by ferdzz
My mistake, i just figured i put it under the wrong category

No problem. But if you request, we can move threads, and in fact I will move this one and leave a re-direct in its old position.