Sadasy的Unity学习笔记——Unity的平滑/缓冲旋转(二)

Quaternion.Lerp()

翻译:Quaternion,四元数;Lerp,插值(一般指线性插值)

官方描述:该函数通过第三个参数向第一个和第二个参数之间进行插值,并规范化结果。
个人理解:第一个参数是当前的角度,第二个参数是期望旋转到的角度,第三个参数代表想使用的时间。

args:
Quaternion from,起始角度
Quaternion to,期望角度
float time,期望时间,此处需要使用Time.deltaTime

在这里插入图片描述
相较于Mathf.SmoothDampAngle函数,该函数需要的参数较少。并且可以围绕指定物体进行旋转。
如果需要原地旋转,那么target参数填写为摄像机本身即可

需要记录摄像机的最大旋转速度(x和y轴),y轴上的最大旋转角度
需要记录当前的x和y值
需要记录time的值

    public Transform target;//相机的目标
    private float xSpeed = 10;//x轴的旋转速度
    private float ySpeed = 5;//x轴的旋转速度
    public float yMin = -70;//y最小角度
    public float yMax = 70;//y最大角度
    public bool needDamping = true; //是否需要的阻尼
    private float damping = 5;//阻尼 
    private float x = 0;//记录当前的x指
    private float y = 0;//记录当前的y值
    void Start()
    {
    
    
        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;
    } 

    void LateUpdate()
    {
    
    
        //如果点击在了UI上,则旋转无效
        if (SceneAndUIManager.instance.uIGameObject.isPointerOverGameObject) return;
        
        //确认是否存在旋转中心点
        if (target)
        {
    
    
            //使用鼠标光按钮来控制相机,调整Camera的角度
            if (Input.GetMouseButton(0))
            {
    
    
                x += Input.GetAxis("Mouse X") * xSpeed ;
                y -= Input.GetAxis("Mouse Y") * ySpeed;
                y = ClampAngle(y, yMin, yMax);
            }

            Quaternion rotation = Quaternion.Euler(y, x, 0);
            //如果不需要阻尼,则直接旋转到该位置
            if (needDamping)
            {
    
    
                transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * damping);
            }
            else
            {
    
    
                transform.rotation = rotation;
            }
        }
    }

    //限制旋转角度
    float ClampAngle(float angle, float min, float max)
    {
    
    
        if (angle < -360)angle += 360;
        if (angle > 360) angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }

猜你喜欢

转载自blog.csdn.net/qq_36423720/article/details/106001162