-5

I need to make a boat move in its opposite direction when it hits out of bounds (8, -8).

The boat moves but adding its current velocity to its current position. If the boat hits a boundary it turns around and moves in the opp. direction...

    }

public void move(int direction)
{
    this.position = position + direction;
    this.velocity = velocity + position;
    if ( position > 5)
    {
        direction = - 1;

    }
    else if ( position < -5)
    {
        direction = + 1;
    }


    }
}

It does not work.. Any help would be great.

Thank you :)

  • You could take a look at [this example](http://stackoverflow.com/questions/14432816/how-to-move-an-image-animation/14436331#14436331), which is simple animation... – MadProgrammer Sep 18 '13 at 06:59

1 Answers1

1

I would modify the code to:

public void move(int direction)
{    
    if ( position > 5)
    {
        direction = - 1;    
    }
    else if ( position < -5)
    {
        direction = + 1;
    }
    this.position = position + direction;
    this.velocity = velocity + position;
}

First set the direction to +/-1 (according to your logic) and only then change the position!

The way you currently do it - it has no effect cause only after you preformed the "move" you change the value of direction (which is a local variable) and finish the execution of the method (then the value of this local variable is erased).

By the way:

  1. you're not "covering" the case where position == 5 (maybe it's made on purpose ?)
  2. if you're setting the direction inside the method - why bother passing it in the method's signature ?
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • Shouldn't direction be either `1` OR `-1`. Adding or subtracting may not change the direction so much as slow down or speed up the movement....? – MadProgrammer Sep 18 '13 at 06:52
  • @MadProgrammer Either I didn't understand your comment or (even though it's correct) its not related to my answer. – Nir Alfasi Sep 18 '13 at 06:54
  • No, you're doing exactly what I said, I'm seeing `= -1` as `-=` and `= +1` as `+=` - my bad – MadProgrammer Sep 18 '13 at 06:58