Mathf.Clamp 正在将我的 eulerangle 重置为 Unity 3D 中的 minValue

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

Mathf.Clamp 在达到最大值时将我的欧拉角重置为最小值,而不是将其限制在最大值。我试过这个:

            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;我被困在这个问题上,不知道如何解决它。任何帮助将不胜感激。

如果你的

lowLimit = 0highLimit = 180,还有你运行:

while (rotation.y > 180)
{
  rotation.y -= 360; 
}

如果在这种情况下你的旋转是最大值 (180),那么 rotation.y 将等于 -180 (180 - 360 = -180)。

那你的钳子就是Mathf.Clamp(-180, 0, 180) // 0

如果您试图将 y 旋转保持在该范围内,那么删除 while 应该可以解决问题。如果您想要不同的效果,我们将需要更多信息。

因为旋转是四元数

并且它们会转换为范围为 [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;