FINAL EDIT: Please read all replies of the accepted post. Here’s the final code:
private void ControlHead(Transform target)
{
Vector3 targetPosition = new Vector3(target.position.x, 0, target.position.z);
Vector3 headPosition = new Vector3(myHead.position.x, 0, myHead.position.z);
Vector3 relativePos = targetPosition - headPosition;
float angle = Vector3.SignedAngle(transform.forward, relativePos, Vector3.up);
float clampedAngle = Mathf.Clamp(angle, -90, 90);
myHead.localRotation = Quaternion.Euler(0, clampedAngle, 0);
}
How would I stop my NPC’s head from looking behind when looking at a target? It seems the clamping is only happening in world space so no matter what direction the parent body is facing, the head will clamp at the same position.
The code:
**
private void ControlHead(Transform target)
{
Vector3 relativePos = target.position - myHead.position;
float angle = Quaternion.LookRotation(relativePos).eulerAngles.y;
float clampedAngle = Mathf.Clamp(angle, -90, 90);
myHead.localRotation = Quaternion.Euler(0, clampedAngle, 0);
}
**
EDIT: please look at the replies to Captain_Pineapple’s answer.
EDIT: video of the issue: https://youtu.be/Tdxkq8g7jKQ