I have a Unity NavMeshAgent that walks around the player. The agent has a "head" that looks at the player independent of the body. This works except when it walks past the player the head rotates way too much - it isn't clamped. I need to clamp the rotation so that it only turns as much as a human neck.
I tried clamping it myself which works fine when the agent is looking straight ahead but when the agent rotates, my clamping is off:
void LateUpdate()
{
Vector3 playerHead = GetPlayerHead();
head.LookAt(playerHead);
float clampedAngleY = head.eulerAngles.y;
if (clampedAngleY >= 180 && clampedAngleY <= 315)
{
clampedAngleY = 315;
}
else if (clampedAngleY >= 45 && clampedAngleY <= 315)
{
clampedAngleY = 45;
}
head.eulerAngles = new Vector3(head.eulerAngles.x, clampedAngleY, head.eulerAngles.z);
}
How do I factor in the agent's rotation?
I've tried subtracting the agent's rotation, performing my clamping then re-applying the rotation but that just behaves odd:
void LateUpdate()
{
Vector3 playerHead = GetPlayerHead();
head.LookAt(playerHead);
float clampedAngleY = head.eulerAngles.y - transform.eulerAngles.y;
if (clampedAngleY >= 180 && clampedAngleY <= 315)
{
clampedAngleY = 315;
}
else if (clampedAngleY >= 45 && clampedAngleY <= 315)
{
clampedAngleY = 45;
}
clampedAngleY = transform.eulerAngles.y + clampedAngleY;
head.eulerAngles = new Vector3(head.eulerAngles.x, clampedAngleY, head.eulerAngles.z);
}