I am making a game involving 2D turrets. The turrets need to rotate around the z-axis and aim at the closest gameobject on the screen automatically. Isolating just the aiming portion, here are two ways I found on the internet:
Vector3 lookDirection = target.transform.position - transform.position;
float angle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;
Quaternion newRotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 2f);
and
Vector3 lookDirection = target.transform.position - transform.position;
Quaternion newRotation = Quaternion.LookRotation(lookDirection);
newRotation.x = 0; newRotation.z = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 2f);
Both work pretty well, but if I use the second one, the turret will flip around and point backwards at its target if the target moves “behind” the turret (on the x axis). I haven’t seen any problems with the first one.
Could anyone tell me what the difference is, or more specifically, why the second one doesn’t work?