首页 > 解决方案 > Mathf.Clamp 在 Unity 3D 中将我的 eulerangle 重置为 minValue

问题描述

Mathf.Clamp 在达到 maxValue 时将我的 eulerangle 重置为 minValue,而不是将其限制在 maxValue。我试过这个:

            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;

和这个 :

         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;

在这两种情况下,我的 lowLimitY = 0 和 highLimitY = 180;我被困在这个问题上,不知道如何解决它。任何帮助将不胜感激。

标签: c#unity3dquaternionseuler-anglesclamp

解决方案


因为旋转是四元数

并且它们被转换为范围为 [0-360) 的欧拉角,因此while (rotation.y > 180)永远不会起作用。

您需要单独跟踪旋转值,钳制到所需值,然后将其应用于对象的旋转。

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

推荐阅读