2D Top Down Player always look at mouse position

I have a 2D topdown shooter in the works, that’s set up on the x and y axis. I’m trying to get my player’s character(a spaceship) to always face the mouse so that they coordinate themselves based on where they will be shooting.

I have the code below working almost as intended, but the rotation is inverted based on where the mouse is. For instance, if I move my mouse from 12 to 6 o clock, in a clockwise direction, the ship will rotate counter clockwise at the same time.

``````        mousePos = Input.mousePosition;
objectPos = Camera.main.WorldToScreenPoint(targetPlayer.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
playerRotationAngle = Mathf.Atan2 (mousePos.y,mousePos.x) * Mathf.Rad2Deg;

transform.rotation = Quaternion.Euler (new Vector3(0,0,playerRotationAngle));
``````

My questions are:

1. What can I change in the transform.rotation z position that can fix this.

2. Is there a better way? I tried using a Raycast, but the ship would rotate on the y axis, instead of the z making movement a nightmare.
(as seen in this video:- YouTube)

First, usually when people say “Top Down” they are referring to a camera up in the ‘Y’ direction looking down on the XZ plane.

As for the code, I see one issue. You use ‘targetPlayer.position’ in your WorldToScreenPoint(), but you are using target.rotation in the last line. This code will only work if both are the same object. Note I ran a quick test using a default scene and this fix, and the code worked fine.

Beyond that, your setup will have to be the default setup for this code to work. That is, the camera has to be looking towards positive ‘z’. If you’ve reversed the direction the camera is looking, you may be able to fix it by reversing the parameters you pass to Mathf.Atan2().

Also make sure whatever game object you are rotating has a natural vertical orientation. For example Unity’s Quad or Sprite will work.

Nice. Thank you.