Unity rotation angle range limit

Because Unity uses quaternion or matrix when doing rotation, sometimes it is inconsistent with the value displayed on the Transform component panel. In addition, all our conventional values ​​of rotation angle are actually in the range of -360-360 degrees, so let's make a judgment. Limit the range of rotation angles:

public float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
        {
            angle += 360;
        }

        if (angle > 360)
        {
            angle -= 360;
        }
        return Mathf.Clamp(angle, min, max);
    }

Get the axis to control the rotation of the object:

 if (Input.GetKey(KeyCode.UpArrow))
    {
        paoGuanAngleX -= Time.deltaTime * 10F;
    }
    else if (Input.GetKey(KeyCode.DownArrow))
    {
        paoGuanAngleX += Time.deltaTime * 10F;
    }
    paoGuanAngleX = ClampAngle(paoGuanAngleX, minRotX, maxRotX);
    Quaternion quaternion = Quaternion.Euler(paoGuanAngleX, 0, 0);
    paoGuan.transform.localRotation = quaternion;

Full code:

public paoGuan;                                    //旋转目标
public float minRotX=-20.0f,maxRotX=3.0f;          //限制角度区间范围
private float paoGuanAngleX;

 void Start()
{
    paoGuanAngleX = paoGuan.localEulerAngles.x;   //旋转的是局部坐标
    paoGuanAngleX = -5.0f;                        //物体X轴初始角度
}

void LateUpdate()                                 //这里也可以改获取轴向控制
{
   if (Input.GetKey(KeyCode.UpArrow))
   {
       paoGuanAngleX -= Time.deltaTime * 10F;
   }
   else if (Input.GetKey(KeyCode.DownArrow))
   {
       paoGuanAngleX += Time.deltaTime * 10F;
   }
   paoGuanAngleX = ClampAngle(paoGuanAngleX, minRotX, maxRotX);
   Quaternion quaternion = Quaternion.Euler(paoGuanAngleX, 0, 0);
   paoGuan.transform.localRotation = quaternion;
}

Guess you like

Origin blog.csdn.net/Abel02/article/details/117414568