Unity3D實現(xiàn)攝像機鏡頭移動并限制角度
本文實例為大家分享了Unity3D實現(xiàn)攝像機鏡頭移動并限制角度的具體代碼,供大家參考,具體內容如下
攝像機鏡頭跟隨鼠標移動,并限制上下左右的移動角度
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軸旋轉的角度(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軸旋轉的角度(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,而沒有負數(shù),那么這將會復雜化我們角度的判斷,如限制左右角度為-60-60之間,那么我們就要判斷角度是否超過300度或是超過60度, 顯然超過300度的角度必定超過60度,那么就需要另外加條件進行判斷;因此對獲取的值進行轉化更為方便!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
c#檢測usb設備撥插類庫USBClassLibrary分享
這篇文章主要介紹了c#檢測usb設備撥插類庫USBClassLibrary的簡單示例,需要的朋友可以參考下2014-04-04
C#實現(xiàn)動態(tài)數(shù)據(jù)繪圖graphic的方法示例
這篇文章主要介紹了C#實現(xiàn)動態(tài)數(shù)據(jù)繪圖graphic的方法,結合實例形式分析了C#根據(jù)動態(tài)數(shù)據(jù)繪制2D數(shù)據(jù)表格的相關操作技巧,需要的朋友可以參考下2017-09-09
c# String擴展 讓你在PadLeft和PadRight時不再受單雙字節(jié)問題困擾
這篇文章主要介紹了c# String擴展 讓你在PadLeft和PadRight時不再受單雙字節(jié)問題困擾,需要的朋友可以參考下2020-04-04
Unity 從Resources中動態(tài)加載Sprite圖片的操作
這篇文章主要介紹了Unity 從Resources中動態(tài)加載Sprite圖片的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04

