2D Mouse Aiming (90852)

Hey guys, I’m creating a 2D sidescroller game and I came across a problem I can’t resolve, I’ve Spent 2 Days googling “2d mouse aiming” and others but I can’t find any luck, can someone at least give a suggestion or a script that allows “2d mouse aiming” (an object that actually looks at the mouse cursor and rotates the object on its z axis) on a Sprite or Gameobject in 2d space?

2 Answers

2

There have been half a dozen different posts this issue at least since Unity 4.3 came out. I believe most of the code posted should do the job. Here is yet another implementation…a bit different than the other’s I’ve seen:

#pragma strict

function Update () {
	var pos = Camera.main.WorldToScreenPoint(transform.position);
	var dir = Input.mousePosition - pos;
	var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
	transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); 
}

sadly this doesn't work, I'm actually planning to modify this hoping it will work

–

oh thanks it finally works

–

For me robertbu first answer worked, its just simple trigonometry which will most likely be more efficient and accurate than using a gameObject tracking the cursors position.

–

how to decrease the speed of rotation @robertbu ,how do u decrease the speed of the rotation