1

Ok, so say you're playing a top down game. You press W and D to go in the up-right direction. Now you just want to go right, so you release the W key. One would expect you to then change directions and head right, but instead, you continue up-right. What can I do to solve this problem? Here is my code:

        if (kb.IsKeyDown(Keys.W) || kb.IsKeyDown(Keys.A) || kb.IsKeyDown(Keys.S) || kb.IsKeyDown(Keys.D))
        {
            if (kb.IsKeyDown(Keys.W))
                velocity.Y = -movespeed;
            else if (kb.IsKeyDown(Keys.A))
                velocity.X = -movespeed;
            else if (kb.IsKeyDown(Keys.S))
                velocity.Y = movespeed;
            else if (kb.IsKeyDown(Keys.D))
                velocity.X = movespeed;
            else if (kb.IsKeyDown(Keys.W) && kb.IsKeyDown(Keys.D))
            {
                velocity.X = movespeed;
                velocity.Y = -movespeed;
            }
            else if (kb.IsKeyDown(Keys.W) && kb.IsKeyDown(Keys.A))
            {
                velocity.X = -movespeed;
                velocity.Y = -movespeed;
            }
            else if (kb.IsKeyDown(Keys.S) && kb.IsKeyDown(Keys.D))
            {
                velocity.X = movespeed;
                velocity.Y = movespeed;
            }
            else if (kb.IsKeyDown(Keys.S) && kb.IsKeyDown(Keys.A))
            {
                velocity.X = -movespeed;
                velocity.Y = movespeed;
            }
        }
        else
            velocity *= .9f;

        position += velocity;
Machavity
  • 30,841
  • 27
  • 92
  • 100
omni
  • 580
  • 1
  • 6
  • 16

1 Answers1

1

So I figured out the answer myself after a few hours of struggle.

Simply setting the velocity to zero before the checks worked: EDIT: multiplying it by .89 actually made for much smoother movement.

        if (kb.IsKeyDown(Keys.W) || kb.IsKeyDown(Keys.A) || kb.IsKeyDown(Keys.S) || kb.IsKeyDown(Keys.D))
        {
            velocity *= .89f
            if (kb.IsKeyDown(Keys.W))
                velocity.Y = -movespeed;
            if (kb.IsKeyDown(Keys.A))
                velocity.X = -movespeed;
            if (kb.IsKeyDown(Keys.S))
                velocity.Y = movespeed;
            if (kb.IsKeyDown(Keys.D))
                velocity.X = movespeed;
        }
        else
            velocity *= .9f;
omni
  • 580
  • 1
  • 6
  • 16