使用Mathf.Clamp()限制对象旋转的问题

时间:2014-09-13 01:10:36

标签: object unity3d rotation clamp

我正在研究一种在z轴上旋转物体的游戏。我需要将总旋转限制在80度。我尝试了以下代码,但它不起作用。 minAngle = -40.0f和maxAngle = 40.0f

Vector3 pos = transform.position;
pos.z = Mathf.Clamp(pos.z, minAngle, maxAngle);
transform.position = pos;

2 个答案:

答案 0 :(得分:7)

您发布的代码会锁定z位置。你想要的是使用transform.rotation

void ClampRotation(float minAngle, float maxAngle, float clampAroundAngle = 0)
{
    //clampAroundAngle is the angle you want the clamp to originate from
    //For example a value of 90, with a min=-45 and max=45, will let the angle go 45 degrees away from 90

    //Adjust to make 0 be right side up
    clampAroundAngle += 180;

    //Get the angle of the z axis and rotate it up side down
    float z = transform.rotation.eulerAngles.z - clampAroundAngle;

    z = WrapAngle(z);

    //Move range to [-180, 180]
    z -= 180;

    //Clamp to desired range
    z = Mathf.Clamp(z, minAngle, maxAngle);

    //Move range back to [0, 360]
    z += 180;

    //Set the angle back to the transform and rotate it back to right side up
    transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, z + clampAroundAngle);
}

//Make sure angle is within 0,360 range
float WrapAngle(float angle)
{
    //If its negative rotate until its positive
    while (angle < 0)
        angle += 360;

    //If its to positive rotate until within range
    return Mathf.Repeat(angle, 360);
}

答案 1 :(得分:1)

这里是Imapler的一个很好的解决方案的静态版本,它不是改变角度本身,而是返回campled角度,因此它可以用于任何轴。

public static float ClampAngle(
    float currentValue,
    float minAngle,
    float maxAngle,
    float clampAroundAngle = 0
) {
    return Mathf.Clamp(
        WrapAngle(currentValue - (clampAroundAngle + 180)) - 180,
        minAngle,
        maxAngle
    ) + 360 + clampAroundAngle;
}

public static float WrapAngle(float angle)
{
    while (angle < 0) {
        angle += 360;
    }
    return Mathf.Repeat(angle, 360);
}

或者,如果您不希望使用WrapAngle方法,那么这里是一个一体化版本

public static float ClampAngle(
    float currentValue,
    float minAngle,
    float maxAngle,
    float clampAroundAngle = 0
) {
    float angle = currentValue - (clampAroundAngle + 180);

    while (angle < 0) {
        angle += 360;
    }

    angle = Mathf.Repeat(angle, 360);

    return Mathf.Clamp(
        angle - 180,
        minAngle,
        maxAngle
    ) + 360 + clampAroundAngle;
}

现在你可以这样做:

transform.localEulerAngles.x = YourMathf.ClampAngle(
    transform.localEulerAngles.x,
    minX,
    maxX
);