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

Mathf.SmoothDampAngle()

翻译:smooth:平滑;damp:阻尼;angle:角度

官方描述:该函数能够随着时间推移,改变一个指定的角度到一个期望的角度。
个人理解:同上。

args:current,指定角度
target,目标角度
currentVelocity,速率(这个还没弄明白)
smoothTime,改变时间
在这里插入图片描述
需要记录当前所在角度、旋转后的角度、旋转速率、旋转的时间。x和y轴共需要8个参数。
这里把x和y的旋转时间统一为rotateBuffTime,则需要七个参数
其次,由于旋转速度需要重新定义,xy各一个参数
最后,由于需要限制鼠标上下移动造成的旋转,需要有一个最大最小角度的限制,两个参数。共计11个参数。
//该脚本需要挂载在摄像机上,并且只能原地旋转

   public void SmoothRotate_1:MonoBehaviour
    {
    
    
       public float xCurrent,yCurrent,xVelocity,yVelocity;
       public float rotateBuffTime;
       public float xSpeed,ySpeed;
       public float yMin,yMax;
    
       void Start()
       {
    
    
          //记录当前所在的角度
          Vector3 angle=transform.eulerAngle;
          xCurrent=angle.x;
          yCurrent=angle.y;
       }

       void FixedUpdate() 
       {
    
    
            //当鼠标按下的时候,开始记录鼠标的偏移。
           //mouse x的值放在y轴上,mouse y 的值放在x轴上
         if(Input.GetMouseButton(0))
         {
    
    
            xTarget=xCurrent+Input.GetAxis("Mouse X")*xSpeed;
            yTarget=yCurrent-Input.GetAxis("Mouse Y")*ySpeed;
            yTarget=ClampAngle(yTarget,min,max);//限制y轴上的旋转
         }
         xCurrent=Mathf.Smooth(xCurrent,xTarget,xVelocity,rotateBuffTime);
         yCurrent=Mathf.Smooth(yCurrent,yTarget,yVelocity,rotateBuffTime);
         transform.rotation=Quaternion.Euler(y,x,0);
       }
       /// <summary>
       /// 限制输入的值在-360到360之间
       /// </summary>
       /// <param name="angle">输入的值</param>
       /// <param name="min">最小值</param>
       /// <param name="max">最大值</param>
       /// <returns></returns>
       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/105800043