Friday, January 20, 2012

XNA Tutorial: Sprite Rotation

When I was learning XNA this was one of the things I always wondered how to do. Since then I have learned how to do it and thought it was about time I shared my knowledge. For this tutorial I'm going to show you how to rotate a texture, how to rotate it to point towards another point and how to move the sprite towards that point.

Here is the image I used
First things first open up visual studio and start a new windows game project. Next copy the image above or get your own and add it to your project. Its important to note that the orientation of the image is important. The front of your object should be pointing towards the right.

Next go to your Game1.cs file just below where the spritebatch is declared and declare the variables you will need.
Now go to the LoadContent method and initialize the variables. The speed variable will be used later.
Next up is the Update method. In this tutorial I'm going to use the mouse position as the point the sprite will rotate towards. So lets get the state of the mouse. Were going to use the mousePosition variable to hold the X, Y position of the mouse. Next were going to get the direction vector. We do this by subtracting the mousePosition from the position of our sprite. But we can't use this yet we need to normalize the direction to turn it into a unit vector. We can now use this to find the rotation by using the Math.Atan2 method. I have no idea of the maths behind this method but it works.
Math.Atan2 works on doubles so remember to cast to direction y/x to doubles and also as this method returns a double, remember to add another cast but this time to a float.

Finally we get to the Draw method. One thing to note here is to make sure you have the origin set to the center of your image. So here I'm dividing the width and height of the image by 2 and setting that to be the origin. It is possible to set the origin to be anywhere on your image and the image should rotate around that origin.
If you run this the rocket should point towards your mouse cursor. If you can't see your cursor go to the Initialize method and write: this.IsMouseVisable = true.

Now to make your rocket move towards your mouse cursor at a constant speed. Go to the Update method and just after you set the rotation write the following.
To get this effect you simply multiply the speed you want your rocket to go by the direction vector we calculated earlier and then add this to the position of your rocket.

If you run the project now you should see the rocket follow your mouse cursor no matter where it is.


This is how it should look.

And there ends my first XNA tutorial. If you see any errors or have any questions please leave a comment below.

4 comments:

  1. Wow great blog entry! Saw you have a sexy assed computer today, nice Android sticker on the back! :D

    ReplyDelete
  2. Great tutorial, has helped me a lot. Thanks.

    ReplyDelete