溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Unity3D實現(xiàn)攝像機鏡頭移動并限制角度的方法

發(fā)布時間:2020-07-27 11:27:43 來源:億速云 閱讀:606 作者:小豬 欄目:編程語言

這篇文章主要講解了Unity3D實現(xiàn)攝像機鏡頭移動并限制角度的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

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

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, 0);
      this.transform.Rotate(0, x * speed, 0, Space.World);
    }
  }

  /// <summary>
  /// 限制相機左右視角的角度
  /// </summary>
  /// <param name="angle">角度</param>
  private void LimitAngle(float angle)
  {
    vect = this.transform.eulerAngles;
    //當前相機x軸旋轉(zhuǎn)的角度(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, vect.y, 0);
  }
  /// <summary>
  /// 限制相機上下視角的角度
  /// </summary>
  /// <param name="angle"></param>
  private void LimitAngleUandD(float angle)
  {
    vect = this.transform.eulerAngles;
    //當前相機y軸旋轉(zhuǎn)的角度(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>
  /// 將角度轉(zhuǎn)換為-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方法進行說明

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

看完上述內(nèi)容,是不是對Unity3D實現(xiàn)攝像機鏡頭移動并限制角度的方法有進一步的了解,如果還想學習更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI