Rotate to cursor in 2D in Unity
Objective: Allow the player to aim with the mouse and change the cursor icon
In a any game you will probably want to disable the default cursor image and replace it with something different. I created a simple crosshair in photoshop and dropped it into my Unity project. I then created an empty game object called CustomCursor and added a child object that has my aim sprite attached.
I created a script that is for the players turret. It will rotate towards where the player is aiming. For this I need a rotationSpeed, and a GameObject that will hold the cursor image I dropped in earlier. This means that if the player is moving one way they can still aim a different way with the mouse and still fire.
I have set my rotation speed to be 60 but you can adjust that to a level that is good for your game.
In the script for the turret I have made a method called AimMouse and this is responsible for the position of the mouse and the rotation of the turret towards that position.
- Get a direction vector that we can use to know the angle needed to rotate.
- Use Mathf.Atan2 to get that angle. I would suggest using the -90f here. If you take that off you might get a small offset to where you’re actually pointing the mouse. See below.
3. Create a Quaternion rotation for the AngleAxis, use the angle create before and the forward direction.
4. Apply the rotation using slerp, which will move the turret smoothly over the given time (rotation speed * Time.deltatime).
5. Create a variable for the current mouse position
6. Apply the mouse position to the new cursor gameobject that has been created.
The last thing to do in the script is to disable the default cursor. In the start method have the following line:
And that should be it for rotating an object towards a position in Unity2D.
Next I will show you how to add in the aiming line.