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.