# Moving a 2d sprite in the direction it's facing

I am currently trying to move a sprite in the direction it’s facing. I have looked through stack overflow and have tried what they said to do but it just won’t work. I don’t really know trig or how to apply it.
This is my code for movement:

if (kbstate.IsKeyDown(Keys.Left))
{
angle -= .7f;
}
if (kbstate.IsKeyDown(Keys.Up))
{
shipPos.Y -= shipSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
//want to change
}
if (kbstate.IsKeyDown(Keys.Right))
{
angle += .7f;
}
if (kbstate.IsKeyDown(Keys.Down))
{
shipPos.Y += shipSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
}

This is how I draw the character:

_spriteBatch.Draw(shipTexture, shipPos, new Rectangle(0, 0, shipSize, shipSize), Color.White, MathHelper.ToRadians(angle), origin, 1f, SpriteEffects.None, 1);

What code should I add to make the sprite move in the direction it’s facing?

Thank you for the source (I don’t know how I missed this), but whenever I use the forwards key, It moves me in a seemingly random direction.
This is how I added the code:

if (kbstate.IsKeyDown(Keys.Up))
{
Vector2 direction = new Vector2((float)Math.Cos(angle),
(float)Math.Sin(angle));
direction.Normalize();
shipPos += direction * shipSpeed/20;
//Without the /20, the ship moves off of the screen too fast to see
}
1 Like

You don’t need to set your direction when you press the up key.

When you press up, you should just advance the position.

Perhaps use left/right to set the angle, and THEN derive a new direction from THAT new angle.

2 Likes