Reputation: 359
I'm making a program (in java) that when you press a start button it makes a line (created by making a oval that moves but not cleaning the screen) that bounces off the JWindow walls. I have three files: a main one with the main method, another one with ounceThreadFrame code, and a last one with the ball code. It all works, except the line dosen't bounce off the left side of the screen. How should I change it so that it bounces of the left side? Let me know if you need the rest of the code. This following code is the code of the ball move() method.
Graphics g=box.getGraphics();
g.fillOval(x, y, xsize, ysize);
x += dx;
y += dy;
Dimension d=box.getSize();
if (x<0){
x=0;
x= dx;
}
if (x+xsize>=d.width){
x=d.width-xsize;
dx= -dx;
}
if (y<0){
y=0;
dy= -dy;
}
if(y+ysize>=d.height){
y=d.height-ysize;
dy= -dy;
}
g.fillOval(x,y,xsize,ysize);
}
Upvotes: 0
Views: 65
Reputation: 1504052
This is the problem:
if (x<0){
x=0;
x= dx;
}
That's setting x
twice, and not changing dx
. In every other block you're changing the position and then reversing the direction. I suspect you want:
if (x < 0) {
x = 0;
dx = -dx;
}
Upvotes: 4
Reputation: 88478
The problem is with the statement x= dx;
I think you know what it should mean. It is just a typo. Happens all the time.
Upvotes: 0