The goal is to swivel the body of the turret (and thus the head) towards a target, and also tilt the head up and down to aim at the target.
The body swivels fine. however, the head refuses to swivel properly, it's like it is 90 degrees off. The axis of the head and body are all pointing the same direction initially. Here is my script:
// Handle base side to side rotation
Vector3 localTarget = transform.InverseTransformDirection(Target.transform.position - transform.position);
float targetAngle = Mathf.Atan2(localTarget.x, localTarget.z) * Mathf.Rad2Deg;
float adjustedAngle = Mathf.Lerp(0, targetAngle, Time.deltaTime * SwivelSpeed);
transform.Rotate(Vector3.up, adjustedAngle);
// Handle head up/down swivel
localTarget = Head.transform.InverseTransformDirection(Target.transform.position - Head.transform.position);
targetAngle = Mathf.Atan2(localTarget.z, localTarget.y) * Mathf.Rad2Deg;
adjustedAngle = Mathf.Lerp(0, targetAngle, Time.deltaTime * SwivelSpeed);
Debug.Log(targetAngle);
Head.transform.Rotate(Vector3.right, adjustedAngle);
Here is a screenshot with the turret base (and thus the head, and everything attached), showing its orientation. This is when Unity is not running:
Same thing, with just the 'Head' selected. Again, it has the same orientation as the base.
Here it is, after I run unity and tell it to face the small sphere:
Any suggestions on why this is happening? I wonder if it has anything to do with the head being local to the body, so the target isn't really comparing against the 'real' coordinates?