0

im a newbie and im learning java just week ago. I wonder how i cant make the ball bounce in one axis only (the X axis)
im not good in logic:( and i want that logic to be in one event.

if(x<0){
++x;//go right
}else if(x>500)
{--x;//go left
}

please help me. Thanks.

3
Contributors
12
Replies
13
Views
5 Years
Discussion Span
Last Post by autorunman22
0

In English:
if x is less than zero go right one step
if x is greater than 500 go left one step
therefore
if x is between 0 and 500 do nothing
... but it should continue to move in whatever its current direction is.

Think about keeping track of its current direction, moving that way while the ball is in range, and changing the direction when the ball reaches 0 or 500.

If in doubt, write it down in English and run through a few cases on a piece of paper to get the algorithm right before you try to code it in Java.

Edited by JamesCherrill: n/a

0

yeah i used to write down the codes in paper before in pc. Im thinking to create a method to go right and method to go left but i want it to be in one event :| im nearly giving up with this.

0

Hint.
When people animate things moving around the screen they usually have variables to hold the h & v velocity of the object (that's the amount by which the x and y positions change in each time cycle). So every time cycle its just
xPosition = xPosition + xVelocity; (ditto for y)
if xVelocity is (say) +1 the object will move slowly right. If it's -10 the object will move rapidly left.
Does that help?

0

What do you mean by "one event"? Your terms are unusual.

Hi Norm
I guess (I really really hope) he is using a javax.swing.Timer to control this. Swing Timers generate an event every n mSec, which passes an ActionEvent object to your code. So "event" would be the appropriate term in this case.
J

0

@J Thanks.
One event would trigger one call to a listener which would then determine the new location, etc

0

@JamesCherrill, thanks for that hint. I came up with an idea like this:

int x,y,direction;
if(x<0){dir=1;}
else if(x>500){dir=0;}
if(dir==1){x++;}
else{x--}

uhm, i dont wanna code it until i confirmed. Im not good at logic. Thats my weakness. LOL. And my english either.

0

@JamesCherrill, thanks for that hint. I came up with an idea like this:

int x,y,direction;
if(x<0){dir=1;}
else if(x>500){dir=0;}
if(dir==1){x++;}
else{x--}

uhm, i dont wanna code it until i confirmed. Im not good at logic. Thats my weakness. LOL. And my english either.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.