0

So i have this cube i wish to bounce off the walls, (as for now just x-axis) it moves however when it gets to the end of the frame it moves back and forth instead of going the opposite direction.

    public void moveBox(int dx,int dy)
{
    if(xLeft < 0 || xLeft > frame_width)
    {
        dx = -dx;
    }
    xLeft = xLeft + dx;
    repaint();
}

Heres what i understand from the code if xLeft (aka origin cordinate for cube pass the frame) then dx (which is the speed at which its being moved) turns negative which should flip the direction. and when it goes back to zero a double negative would flip it back to positive. My logic is flawed because its not bouncing its just floats back and forth in the end of the frame

however that is not the case and i don't understand why is it because the method gets recalled with a different xLeft value each time? if thats the case what should i do to make it bounce? I've tried alot of different things nothing seems to fully bounce it back

user3249265
  • 113
  • 1
  • 5
  • 16
  • See if [this answer](http://stackoverflow.com/a/22283611/2587435) helps. Look at the `animate` method in the `Ball` class. – Paul Samsotha Mar 11 '14 at 05:36

1 Answers1

1

xLeft may still be out of bounds after the evaluation, meaning that it will continuously slip into the if statement.

This would occur if the delta is smaller then the amount that the object has passed the boundaries.

You might consider placing the object back on the edge of the boundaries, for example

if(xLeft < 0 || xLeft > frame_width)
{
    dx = -dx;
}

if (xLeft < 0)  
{
    xLeft = 0;
} 
else if (xLeft > frame_width)  
{
    xLeft = frame_width;
} 
else 
{
    xLeft = xLeft + dx;
}

You could drop the else portion if you wanted to and simply move xLeft by the delta...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366