Bootstrap

Unity 相机旋转及角度限制

前言

由于欧拉角具有直观的可读性,做相机旋转时选择修改eulerAngles 来实现旋转,但实际效果与预期稍有不同,这是因为欧拉角受到万向锁(Gimbal Lock)的影响,在赋值时需要对输入的角度进行调整。

if (value < 180)
{
    value = Mathf.Clamp(value, -180, -min);
}
else
{
    value = Mathf.Clamp(value, 360 - max, 360);
}

实现

private void Rotate()
{
    xInput = Input.GetAxis("Mouse X");
    yInput = Input.GetAxis("Mouse Y");

    float xAngle = transCam.eulerAngles.x - yInput * speedRotate;
    float yAngle = transCam.eulerAngles.y + xInput * speedRotate;
    xAngle = Clamp(xAngle, minAngleX, maxAngleX);
    yAngle = Clamp(yAngle, minAngleY, maxAngleY);
    transCam.eulerAngles = new Vector3(xAngle, yAngle, 0);
        
    float Clamp(float value, float min, float max)
    {
        if (min > max)
        {
            float temp = min;
            min = max;
            max = temp;
        }

        if (value < 180)
        {
            value = Mathf.Clamp(value, -180, -min);
        }
        else
        {
            value = Mathf.Clamp(value, 360 - max, 360);
        }
        return value;
    }
}
;