1. 程式人生 > 程式設計 >Unity3D實現攝像機鏡頭移動並限制角度

Unity3D實現攝像機鏡頭移動並限制角度

本文例項為大家分享了Unity3D實現攝像機鏡頭移動並限制角度的具體程式碼,供大家參考,具體內容如下

攝像機鏡頭跟隨滑鼠移動,並限制上下左右的移動角度

public class ViewFromCream : MonoBehaviour 
{
  public int speed=5;
  public Vector3 vect;
  
  private float xcream;
  private float ycream;

  public void Update()
  {
    CreamView();
  }

  private void CreamView()
  {
    float x = Input.GetAxis("Mouse X");
    float y = Input.GetAxis("Mouse Y");
    if (x!=0||y!=0)
    {
      LimitAngle(60);
      LimitAngleUandD(60);
      this.transform.Rotate(-y * speed,0);
      this.transform.Rotate(0,x * speed,Space.World);
    }
  }

  /// <summary>
  /// 限制相機左右視角的角度
  /// </summary>
  /// <param name="angle">角度</param>
  private void LimitAngle(float angle)
  {
    vect = this.transform.eulerAngles;
    //當前相機x軸旋轉的角度(0~360)
    xcream = IsPosNum(vect.x);    
    if (xcream > angle)
      this.transform.rotation = Quaternion.Euler(angle,vect.y,0);
    else if (xcream < -angle)
      this.transform.rotation = Quaternion.Euler(-angle,0);
  }
  /// <summary>
  /// 限制相機上下視角的角度
  /// </summary>
  /// <param name="angle"></param>
  private void LimitAngleUandD(float angle)
  {
    vect = this.transform.eulerAngles;
    //當前相機y軸旋轉的角度(0~360)
    ycream = IsPosNum(vect.y);
    if (ycream > angle)
      this.transform.rotation = Quaternion.Euler(vect.x,angle,0);
    else if (ycream < -angle)
      this.transform.rotation = Quaternion.Euler(vect.x,-angle,0);
  }
  /// <summary>
  /// 將角度轉換為-180~180的角度
  /// </summary>
  /// <param name="x"></param>
  /// <returns></returns>
  private float IsPosNum(float x)
  {
    x -= 180;
    if (x < 0)
      return x + 180;
    else return x - 180;   
  }
}

對IsPosNum方法進行說明

之所以要將獲取的尤拉角轉換為-180°-180°之間,是因為在獲取eulerAngle中,x軸和y軸的值只有0-360,而沒有負數,那麼這將會複雜化我們角度的判斷,如限制左右角度為-60-60之間,那麼我們就要判斷角度是否超過300度或是超過60度, 顯然超過300度的角度必定超過60度,那麼就需要另外加條件進行判斷;因此對獲取的值進行轉化更為方便!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。