Wednesday, 18 September 2013

How to turn an object around and move into the opposite direction?

How to turn an object around and move into the opposite direction?

Considering out of bounds position is 6 and -6.
I want to make the ship turn around and move in the opposite direction.
This is the code I have.. It is still not working 100% how I want it. I am
curious to see if anyone had any ideas how do improve. Here is the logic
of my code.
//If the ship hits a boundary it turns around and moves in
the opp.
//direction. To do this, the ship's velocty should be
flipped from a
//negative into a positive number, or from pos to neg if
boundary
//is hit.
//if ship position is -5 at velocity -1 new ship pos is -6
//if ship position is -6 at velocity -1 new ship velocity
is +1
// new ship position
is +5
Here is my code:
public void move()
{
position = velocity + position;
if (position > 5)
{
velocity = -velocity;
}
else if (position < -5)
{
velocity = +velocity;
}
}

No comments:

Post a Comment