Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm trying to figure out the best way of rotating an object towards the directional input of the user. I'm attempting to mimic making turns on ice skates.

For instance, if the player is moving right and the input is down and left, the player should start rotating to the right a set amount each tick. I'll calculate a new vector based on current velocity and rotation and apply that to the current velocity. That should give me nice arcing turns, correct?

At the moment I've got eight if/else statements for each key combination which in turn check the current rotation:

// Rotate to 225
if (keyboardState.IsKeyDown(Keys.Up) && keyboardState.IsKeyDown(Keys.Left))
{
    // Rotate right
    if (rotation >= 45 || rotation < 225)
    {
        rotation += ROTATION_PER_TICK;
    }
    // Rotate left
    else if (rotation < 45 || rotation > 225)
    {
        rotation -= ROTATION_PER_TICK;
    }
}

This seems like a sloppy way to do this and eventually, I'll need to do this check about 10 times a tick. Any help toward a more efficient solution is appreciated.

share|improve this question
add comment

1 Answer

Vector2 Forward = Vector2.Zero;

if (keyboardState.IsKeyDown(Keys.Up)) Forward+= Vector2.UnitY;
if (keyboardState.IsKeyDown(Keys.Down)) Forward-= Vector2.UnitY;
if (keyboardState.IsKeyDown(Keys.Left)) Forward-= Vector2.UnitX;
if (keyboardState.IsKeyDown(Keys.Right)) Forward+= Vector2.UnitX;

if (forward != Vector2.Zero)
{
   PlayerForward = Vector2.Lerp(PlayerVelocity, Forward, RotationSpeed);
   PlayerForward.Normalize();

   PlayerPosition += PlayerForward * Speed;
}

This can do the trick, though if angle between forward and playerForward is 180º, it won't turn

If you need the angle... you can use this:

 rotation = Math.Atan2(PlayerForward.Y, PlayerForward.X);
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.