- Home /
2d - Follow cursor by having object rotate around z-axis
Using the overhead view how can I move the mouse cursor around the screen while having the object rotate around the z-axis so the object faces the mouse cursor.
I thought something like the code below would work but apparently not. transform.LookAt (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0));
I know very little so if you could explain your code that would be very helpful. Thanks!
Are you using the z axis as up/down? If so try changing world up in Transform.LookAt(Vector3 target, Vector3 worldUp)
, i.e.
transform.LookAt (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0), Vector3.forwards);
and you probably need to transform the mousePosition vector in world space as well :
Vector2 world$$anonymous$$ousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt((Vector3)world$$anonymous$$ousePosition, Vector3.forwards);
Answer by _Gkxd · Apr 09, 2015 at 06:50 AM
In 2D, Mathf.Atan2 is what you need.
To use, if you have two points, (x1, y1) and (x2, y2), the angle from the first point to the second point is Mathf.Atan2(y2-y1, x2-x1)
. Your first point would be the position of your object, and the second point would be the position of the mouse. Set transform.LocalEulerAngle
to (0, 0, /*Atan2 and convert to degrees*/)
and you should get what you want.