I have problem rotating enemy to player, using Unity 2D. Enemy should rotate like he is looking at player, but everytime when the rotation on Z axis is greater than 270 it automaticly lower by 180. Here is my script controling rotation:
var target : Transform;
function Start () {
target = GameObject.FindGameObjectWithTag("Player").transform;
}
function Update () {
var relativePos = target.position - transform.position;
var rotation = Quaternion.LookRotation(relativePos);
rotation.x = Mathf.Clamp(0, 0, 0);
rotation.y = Mathf.Clamp(0, 0, 0);
transform.rotation = rotation;
}
Try this:
function Update () {
var relativePos = target.position - transform.position;
var angle = Mathf.Atan2(relativePos.y, relativePos.x) * Mathf.Rad2Deg;
var rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = rotation;
}
Note the above code assumes that the right side of this sprite is considered forward. If the top is considered forward, then add 90 to the angle before calling AngleAxis().
What about this? (taken from here: http://forum.unity3d.com/threads/transform-lookat-or-quaternion-lookrotation-on-1-axis-only.36377/)
var newRotation = Quaternion.LookRotation(transform.position - target.position);
newRotation.z = 0.0;
newRotation.x = 0.0;
Though I’m not sure about newRotation.z
, I think I’ve done it in my code with the y
field and it worked.
EDIT:
Might need to add Vector3.forward
as a second parameter to LookRotataion
.