# Rotating sprites

I'm a beginner at making games, i'm currently only working in 2D using XNA.

So far all of my games i've been using the following logic for sprite movement:

if(left key pressed)
sprite_x_position --;


This movement is kind of square?

I want to be able to turn the sprite, so that'd be rotating the vector i'm using to store the sprites position?

My vector and matrix math is OK but i'm having a hard to looking for a decent walk through on how to do this?

Any help would be appreciated,

• Honestly, I think there are some things that need to be addressed well before rotating sprites. Thing 1 - your current method for movement may be tied to the keyboard refresh rate (I found this out the hard way :P). Thing 2 - organise everything neatly using classes / structs (as far as I can see, you aren't), or it will become an absolute mess very quickly. – Polar May 30 '13 at 19:26
• The game's constructed using the appropriate classes; Sprite, SpriteManager, StateManager etc. But yes you're right my movement logic has been tied to the keyboard refresh rate - have now changed that. Thanks for the reply! – Lee Brindley Jun 2 '13 at 22:25

Make a new float variable called Rotation

You can use the MathHelper class to provide easy methods to convert degress to radians (the value SpriteBatch accepts)

For example: (I use an origin for the rotation so it rotates around the center)

Rotation = MathHelper.ToRadians(180); //Rotate the sprite 180 degrees
SpriteBatch.Draw(TEXTURE, SPRITE_POSITION, null, Color.White, Rotation, new Vector2(TEXTURE.Width / 2, TEXTURE.Heigh / 2), 1, SpriteEffects.None, 1); //Draw TEXTURE with Rotation


Additionaly, I would recommend creating a sprite class to hold your Texture, Position, Rotation, Velocity, etc.

public class Sprite
{
Texture2D Texture;
Vector2 Position;
float Rotation;

public Sprite(Texture2D texture)
{
Texture = texture;
}
}


This way you can just do Sprite sprite = new Sprite(TEXTURE) and have a nice object oriented approach to accessing it (sprite.Position, sprite.Texture, etc) and will probably help you later in the long run.

One of the bigest mistakes that will hurt you later is not applying elapsed time. If your FPS drops (different computer, running alot of programs, etc) or rises then your sprite will move faster, since it is depending on the update rate. You can solve this by applying elapsed time.

float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
float speed  = 10; //Will need tweaking, I cant remember a good value
if (KeyBoardState.GetState().IsKeyDown(Keys.Left))
{
sprite.Position -= elapsed * speed //Elapsed is so small so we must multiply by speed
}