- Home /
Problem with Quaternion.LookRotation()
I've written a function that's supposed to make a GameObject face another GameObject, and return the resulting Quaternion if I only want to use part of it.
The problem I'm having with it is that if the object is facing away from the target the first time I call the function on it, it faces away from the target rather than towards it (= the rotation is inverted by 180 degrees). If the object is already rotated in the target's general direction, the rotation works fine.
Here's the source for the function I'm using:
Quaternion LookAt2D(GameObject tracker, GameObject target)
{
Vector3 trackerPosition = new Vector3(
tracker.transform.position.x,
tracker.transform.position.y,
0.0f);
Vector3 targetPosition = new Vector3(
target.transform.position.x,
target.transform.position.y,
0.0f);
Quaternion rotation = Quaternion.LookRotation
(targetPosition - trackerPosition, tracker.transform.TransformDirection(Vector3.up));
tracker.transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);
return rotation;
}
Here's the problem in action.
Before starting the scene:
After starting the scene:
Both of the turrets are the exact same GameObject, with the exact same script attached.
Answer by OmegaVesko · Feb 02, 2014 at 05:05 PM
Hah, alright, it looks like I sort of solved my own problem. I just added this code to the beginning of the function, making the object face the target before calculating the rotation.
if (tracker.transform.position.x > target.transform.position.x)
{
tracker.transform.eulerAngles = new Vector3(0, 0, 360);
}
else
{
tracker.transform.eulerAngles = new Vector3(0, 0, 180);
}
I would really like to know why this happens, though. Is it a Unity bug or just a matter of me not understanding Quaternions?