參考方案:以官方的Standard Assets的ThirdPersonCharacter.cs爲例。
最基礎的C#請看這裏→C#入門基礎(一)
ThirdPersonCharacter.cs Part1 | ||||
代碼塊 | 簡介 | 用法 | 放置位置 | |
01 | [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CapsuleCollider))] [RequireComponent(typeof(Animator))] |
請求組件,當掛上腳本的時候,會幫你添加這3個組件 | [RequireComponent(typeof(XXX))],改寫XXX部分 | 繼承MonoBehaviour的類外面 |
02 | [SerializeField] | 在面板序列化顯示,但不想其它腳本訪問它 | 直接加在變量前面,具體請看→這裏 | 繼承MonoBehaviour的類的類裏面,方法的外面 |
03 | [Range(1f, 4f)] | 規定變量的範圍,在面板會出現可以拖動的調節器 | 直接加在變量前面,具體請看→這裏 | 繼承MonoBehaviour的類的類裏面,方法的外面 |
04 |
Rigidbody CapsuleCollider Animator |
物理相關,定義物體的重量等信息 | 這3個是Unity爲你準備好的類,你可以正常使用類的方式,來使用它。 | 一般作爲類聲明,當然不止這3個,相對於膠囊碰撞體,還有一個立方體的碰撞體 |
膠囊碰撞體,用於碰撞檢測 | ||||
動畫狀態機 | ||||
05 | m_Animator = GetComponent<Animator>(); | 用於獲得組件變量 | 基礎C#用法 | void Start()方法裏面 |
06 | m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; | 用於凍結XYZ軸,和你自己在面板上勾選一樣 | 如代碼所示 | void Start()方法裏面 |
07 | Vector3 | 向量 | 基礎C#用法,具體介紹請看→這裏 | 在類或方法裏面 |
先解釋[1]爲什麼要請求對象?
作爲一個人形物體,添加Rigbody、CapsuleColider、Animator是家常便飯的事情,手動添加其實也可以。
一方面,用代碼添加方便選擇並設置,一定程度減少了操作,比如 凍結XYZ軸。
另一方面,產生依賴,即你必須先移除該腳本,才能移除Rigbody、CapsuleColider、Animator,否則會報錯。
第二,magnitude是個敏感詞,它代表空間向量的距離;sqrMagnitude是未開平方的距離,它主要用於比較。
因爲比較sqrMagnitude可以省去開方的資源消耗,所以一旦涉及向量大小比較,優先考慮sqrMagnitude。
magnitude源定義:
public float magnitude
{
get
{
return Mathf.Sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
}
}
sqrMagnitude源定義:
public float sqrMagnitude
{
get
{
return this.x * this.x + this.y * this.y + this.z * this.z;
}
}
magnitude (Read Only)返回向量的長度,也就是點P(x,y,z)到原點(0,0,0)的距離。
sqrMagnitude (Read Only)返回未開方的數據。
參考文檔: