2d sprite look at mouse

Hello,
i´ve been looking around for quite some time now and all i found were scripts that worked odd for me. I have a top down scene where my player (sprite) moves around. I want him alwys to face the mouse coursor. I tried several scripts from around the forums but most of them rotated my sprite in a way that it either got invisible (90 degree to the camera) or, as my last attempt, facing down slowly, the father away the mouse moves.
This is my current script:

void Update () {
		mousePosition = Input.mousePosition;			
		mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
		//transform.LookAt(new Vector3(mousePosition.x, mousePosition.y, transform.position.x)); 
		Quaternion rot = Quaternion.LookRotation( transform.position - mousePosition, Vector3.forward );
		transform.rotation = rot;	
	}

Are there any 2d specific helpers/classes designed for this or do i really need to go down the 3d road here?

Thanks in advance!

1 Like

Found a solution by myself - if anyone has the same problem, this is what iam using now:

void Update () {
		mousePosition = Input.mousePosition;			
		mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

		//transform.LookAt(new Vector3(mousePosition.x, mousePosition.y, transform.position.x)); 
		Quaternion rot = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward );
		transform.rotation = rot;	
		transform.eulerAngles = new Vector3(0, 0,transform.eulerAngles.z); 
	}

The whole Quaternion and Angle stuff is really confusing to me.

Is this the right way for 2d?

4 Likes

I have the same problem!
It should be an overload method of LookRotation for 2D purposes, like the script reference:

static Quaternion LookRotation(Vector2 forward, Vector2 upwards = Vector2.up); // For 2D projects

Some methods and classes works with 3D only, not 2D.
So far my 2D spaceRocks is going well, but to make the enemies face the player… is a hell.
Thanks for the solution!