2D Top-Down Aiming Using the Mouse in Unity3D
Hello, in this short (and first!) post on this blog I would like to show you how to make a sprite face the mouse cursor. This is quite useful for aiming in top-down shooters and similar games. You can see an example of this in this gif.
Now let's talk about the code. I tried various solutions found on the web, but most of them don't work, work sometimes or work badly. Luckily the easiest solution is also the best one! I found it on YouTube and it is made by Danndx.
Here's the full code:
Vector3 mousePosition = new Vector3 (Camera.main.ScreenToWorldPoint(Input.mousePosition)); Vector2 directionToLookAt = new Vector2( mousePosition.x - transform.position.x, mousePosition.y - transform.position.y ); transform.up = directionToLookAt;
If you are in a hurry you can just copy-paste this code into a script on the object you want to rotate and then call it in the function Update. But what does this code actually do?
Explaining the code
Vector3 mousePosition = new Vector3 (Camera.main.ScreenToWorldPoint(Input.mousePosition));
Here we get the current mouse position, we translate it into "world coordinates", which are actually usable, and then store it in a Vector3 variable.
Vector2 directionToLookAt = new Vector2( mousePosition.x - transform.position.x, mousePosition.y - transform.position.y );
Create a new Vector2 and store the difference between the mouse position and the object position. We don't actually need the z axis, so we won't use a Vector3 this time.
transform.up = directionToLookAt;
transform.up "Manipulates a GameObject’s position on the Y axis (green axis) of the transform in world space", according to Unity's Docs. Basically, we rotate the Y axis of the object.