1
votes

I'm working on a simple bit of code in C# to make sure a player model's head points at the mouse's Vector3 position (lookPoint), but that it clamps between a 90 degree range, 45 degrees to either side of the torso's current direction.

I've played around with the results of euler angles to make sure I'm getting the desired rotation value for the y axis, but I struggle with when the euler angle should cycle over to 0 again, and I can't seem to figure out how to sort it out.

 minRot = myTorso.transform.rotation.eulerAngles.y-180f-45f;
 maxRot = myTorso.transform.rotation.eulerAngles.y-180f+45f;

 lookDirection = Mathf.Atan2(lookPoint.x - transform.position.x, lookPoint.z - transform.position.z);
 lookRotation = Mathf.Clamp(Mathf.Rad2Deg * lookDirection, minRot, maxRot);

 myHead.eulerAngles = new Vector3(0,lookRotation,0);

This is causing the head to snap back to one of the extremes when it cannot figure out what it's max or min should be.

Can anyone help me to define the minRot and maxRot so that it accounts for the 180 degree crossover?

1

1 Answers

0
votes

This should do what you're looking for. I'm just basing it off of the variables and code provided, so there's a chance things may not work perfectly. So let me know if it doesn't and we can adjust:

lookDirection = Mathf.Atan2(lookPoint.x - transform.position.x, 
                            lookPoint.z - transform.position.z) * Mathf.Rad2Deg;
Quaternion q = Quaternion.Euler(new Vector3(0, lookDirection, 0));
Quaternion targetRotation = new Quaternion();
Quaternion torsoRotation = myTorso.transform.rotation;
// Check if the angle is outside the 45degree range
if (Quaternion.Angle(q, torsoRotation) <= 45.0f)
    targetRotation = q;
else
{
    // This is to check which direction we're out of range
    float d = Mathf.DeltaAngle(q.eulerAngles.y, torsoRotation.eulerAngles.y);
    if (d > 0.0f)
        target = torsoRotation * Quaternion.Euler(0, -45f, 0);
    else if (d < 0.0f)
        target = torsoRotation * Quaternion.Euler(0, 45f, 0);
}
myHead.rotation = targetRotation;