Search code examples
c#unity-game-enginequaternionseuler-anglesclamp

Mathf.Clamp is resetting my eulerangle to minValue in Unity 3D


Mathf.Clamp is resetting my eulerangle to minValue when it reaches the maxValue instead of constraining it at maxValue. I have tried This :

            rotateX = Input.GetAxis("Mouse X") * senseX;
        player.transform.Rotate(player.up, Mathf.Deg2Rad * rotateX, Space.World);

        playerXRotation = player.eulerAngles;

        while (playerXRotation.y > 180f)
            playerXRotation.y -= 360f;

        Debug.Log("Y Rotation: " + playerXRotation.y);
        playerXRotation.y = Mathf.Clamp(playerXRotation.y, lowLimitY, highLimitY);
        player.transform.eulerAngles = playerXRotation;

And This :

         rotate = Input.GetAxis("Mouse X") * senseX;
         rotation = player.transform.eulerAngles;
         rotation.y += rotate * RateOfRotate;

         while (rotation.y > 180)
         {
             rotation.y -= 360;
         }
         rotation.y = Mathf.Clamp(rotation.y, lowLimitY, highLimitY);
         player.transform.eulerAngles = rotation;

Here my lowLimitY = 0 and highLimitY = 180 in both the cases; I am stuck at this and have no clue how to work around it. Any help will be appreciated.


Solution

  • Because rotations are quaternions

    And they get converted to Euler angles with range [0-360), so while (rotation.y > 180) will never work.

    You need to track the rotation value separately, clamp to desired values, then apply it to the object's rotation.

    rotation = player.transform.eulerAngles;
    float rotationY = rotation.y + rotate * RateOfRotate;
    rotationY = Mathf.Clamp(rotationY, lowLimitY, highLimitY);
    rotation.y = rotationY;
    player.transform.eulerAngles = rotation;