# bouncing ball problem

nick woodward
Ranch Hand
Posts: 370
11
hello!

New code in last post

I've got to make a ball bounce around a screen.... but you'll have to bare with me, i'm learning from the art and science of java, along with the cs106a lectures. From what I can gather they seem to hold back useful java code and give you the bare minimum so that you learn to solve common problems early on. So you might see some odd ways of doing things. well you might anyway.....!

anyway, i've changed the code over and over, and think this is the most succinct way i can manage it. but i have a problem. where i've marked the code (*****) and the following line are conditional on each other. so one won't provide the correct answer without the other line executing first, and vice versa (ignore the code after, i haven't looked at where that should be yet ). Anyway I don't really want to rip the code apart, again, because i'm pretty sure it's close.

thanks a lot,

Nick

*edit: i know the loop won't end that's ok for the time being.

Roger F. Gay
Ranch Hand
Posts: 408
You should be able to simplify with currentX += dX and currentY += dY.
Also, if you want to have the ball bounce all the way around (or back and forth), you don't need the for loops; but you would need to check to see if the ball hits the bottom or left side of the screen as well.

nick woodward
Ranch Hand
Posts: 370
11
Roger F. Gay wrote:You should be able to simplify with currentX += dX and currentY += dY.
Also, if you want to have the ball bounce all the way around (or back and forth), you don't need the for loops; but you would need to check to see if the ball hits the bottom or left side of the screen as well.

really?

how would the code keep track of movement up or left of the screen?

the code below surely allows this because if dY or dX is negative it starts reducing the current X and Y locations.

currentY = dY==-1? currentY--:currentY++;
currentX = dX==-1? currentX--:currentX++;

simply using currentY +=dY wouldn't achieve the same thing.

---

why aren't the for loops necessary? i can't think of a test other than the one that i provided:

dY = currentY == SCREEN_SIZE_V-BALL_SIZE? -1:1;

the problem is that if you use an if statement, say if(currentY<SCREEN_SIZE_V), then that doesn't allow the ball to return to the top of the screen. the second it moves off the bottom it passes the if condition and returns to the bottom of the screen!

>

nick woodward
Ranch Hand
Posts: 370
11
*sigh.

re-did it again from scratch. still has the same problem.

i've updated the comments on the code:

*EDIT: think i'm getting there (yes i know i'm talking to myself, it helps!). New code.

nick woodward
Ranch Hand
Posts: 370
11

GET IN!!!

Roger F. Gay
Ranch Hand
Posts: 408
I keep wondering where your dY *= -1 and dX *= -1 switches are. Top / bottom, Left / right ... each time you hit a boundary you want to reverse the movement horizontally or vertically. You get that by multiplying by -1.