Created an object consisting of many parts, how to correctly rotate one of the parts of an object so that it tracks another object using LookAt if possible? When I use LookAt, part of the first object is rotated sideways, not front.
And also how to rotate an object so that it tracks another object along one axis?
The script below will handle horizontal head movement. Also added a bit where it turns the body if the head reaches its limit. You can remove that.
public float maxAngle = 75;
public Transform target;
public Transform head;
void FixedUpdate {
// Handle the head look rotation
HandleHoodRotation ();
}
void HandleHoodRotation () {
if (CanLook())
head.LookAt(target);
// If you want body movement once you reach the end of neck angle
else
transform.LookAt(new Vector3(target.position.x, transform.position.y, target.position.z));
}
// Checks if we can look at the object
bool CanLook () {
// Get the direction vector for the looked at object
var objectDir = target.position - transform.position;
// Remove the vertical component
var objectDir = new Vector3 (objectDir.x, 0, objectDir.z);
// Get the angle
var angle = Vector3.Angle(objectDir, transform.forward);
// Now do the check
return angle < maxAngle;
}