Often when creating games in 2D you need a sprite to rotate towards another object, whether that be a turret rotating towards an enemy or making something follow your mouse. Regardless of the use of this rotation the principle is the same. In this tutorial I use the basic concept of making something follow the mouse, but the game logic provided should enable you to rotate any sprite towards just about any object on the game screen.
Before we start anything language specific, we should have a think about what exact we want to achieve. We’re going to assume we start with the sprite unrotated, parallel to the X and Y axis (this assumption is just for ease of explanation and doesn’t factor into any calculations). So we begin say, with a sqaure:
With the center of rotation at the middle of the square. In order to rotate this towards distant point we need to do some basic trigonometry. I know this seems scary but it’s really easy as pie, any 15 year old could do this (or probably even younger).
The goal is to rotate the object about the center point so that the leading face (the right hand side of our square) points towards the cursor. To this we image the following scenario:
Where the circle is the mouse pointer.
Basically we want to rotate through the shown angle to face the leading face at a 90 degree angle to the cursor. We do this by doing some really simple maths. We just take the arctangent of the two angles which is supplied in almost every programming language nowadays as:
Or something similar.
Now we have the required rotation, to move the object towards the cursor we minus its current position from the speed we want it to travel by frame * the Cos or Sin of the rotation.
For it’s horizontal movement we subtract speed * Cos(rotation).
For it’s vertical movement we subtract speed * Sin(rotation).
Why Sin of one Cos of the other? Simply because you are essentially making smaller and smaller triangles as you go closer to the point and taking Cos of the rotation finds the horizontal distance of said smaller triangle, and take Sin finds the vertical. It’s basic trigonometry!
Here’s an example of the code for the update parameters in C#:
//Store the mouse state MouseState mouse = Mouse.GetState(); ; //Calculate the distance from the square to the mouse's X and Y position float XDistance = SquarePosition.X - mouse.X; float YDistance = SquarePosition.Y - mouse.Y; //Calculate the required rotation by doing a two-variable arc-tan rotation = (float)Math.Atan2(YDistance, XDistance); //Move square towards mouse by closing the gap 3 pixels per update SquarePosition.X -= (float)(3 * Math.Cos(rotation)); SquarePosition.Y -= (float)(3 * Math.Sin(rotation));
Hopefully this helped! Any questions just ask.
Please note that the source is compiled for windows, and is also compiled for XNA 4.0 CTP! You will also need Visual Studio 2010