trying to get 2D missiles to face my mouse. But having a very hard time, please help.

I’ve been trying to get my 2D object to point in the direction of the mouse. I’ve been looking everywhere online and
and I’ve tried pasting many different pieces of code to get my object to look at the mouse. But none of them seem to
work. This is what I’ve got at the moment for tracking the mouse:

Vector3 mousePos = Input.mousePosition;
mousePos.z = -(transform.position.x - Camera.main.transform.position.x);

Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);

transform.LookAt(worldPos);

I put that code on my object, and it looks like it should work. But when I run it, its not pointed anywhere near the mouse.
and goes in all sorts of directions. I could really use some help on how to figure this out. :frowning:

LookAt will rotate the whole object which you don’t want as with a 2d object forward faces the camera. Instead, just rotate around the axis based on the mouse position. Like this:

		Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);	
		transform.rotation = Quaternion.AngleAxis((Mathf.Atan2(worldPos.y, worldPos.x) * Mathf.Rad2Deg)-90, Vector3.forward);

The -90 is to adjust for if your image point up, if it points right, remove it.

It didn’t really seem to work for me…Now the missile just points straight down. And it doesn’t seems to rotate at all when I move the mouse.

Never mind, I got it to work. I just had to set my camera to Orthographic in the inspector. Thanks for the help! :slight_smile:

Heh, yea a perspective camera will get odd results in 2d. :wink: