[英]unity - camera movement
我正在審查這段關於相機移動的代碼:
using UnityEngine;
using System.Collections;
public class CamMove : MonoBehaviour {
Vector2 mouseLook;
Vector2 smoothV;
public float sensitivity=5.0f;
public float smoothing = 2.0f;
GameObject character;
void Start()
{
//moving left and right
character = this.transform.parent.gameObject;
}
void Update()
{
var md = new Vector2 (Input.GetAxisRaw ("Mouse X"), Input.GetAxisRaw ("Mouse Y")); //mouse movement
md = Vector2.Scale (md, new Vector2 (sensitivity * smoothing, sensitivity * smoothing));
smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
if(mouseLook.y>-40 && mouseLook.y<60)
transform.localRotation = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
character.GetComponent<CharacterController>().transform.localRotation = Quaternion.AngleAxis (mouseLook.x, character.transform.up);
}
}
他如何獲得每個新位置? 使用 Math.Lerp 插值? 另外我無法理解部分md = Vector2.Scale (md, new Vector2 (sensitivity * smoothing, sensitivity * smoothing));
還有部分:
if(mouseLook.y>-40 && mouseLook.y<60)
transform.localRotation = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
好
var md = new Vector2 (Input.GetAxisRaw ("Mouse X"), Input.GetAxisRaw ("Mouse Y")); //mouse movement
甚至評論mouse movement
。 像往常一樣,一個更好的變量名已經可以解釋它了。 最好稱為mouseDelta
。 所以代碼不使用固定的鼠標位置,而是使用自上一幀以來的行進距離。 (見Input.GetRawAxis )
然后
md = Vector2.Scale (md, new Vector2 (sensitivity * smoothing, sensitivity * smoothing));
Vector2.Scale
正在按比例放大或縮小此 Vector。 你也可以把它寫成
md = new Vector2 (md.x * sensitivity * smoothing, md.y * sensitivity * smoothing);
實際上這是完全沒有必要的,因為你可以像這樣寫得更簡單:
md *= sensitivity * smoothing;
然后Mathf.Lerp
是兩個給定位置之間的線性插值,使用0
和1
之間的某個factor
,其中0
將完全是第一個參數, 1
完全是第二個參數,否則介於兩者之間。 例如,因子0.5
將導致兩個值之間的中心,因此這取決於您給定的smoothing
值
smoothV.x = Mathf.Lerp (smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp (smoothV.y, md.y, 1f / smoothing);
同樣,這是不必要的,因為它最好直接使用Vector2.Lerp
smoothV = Vector2.Lerp(smoothV, md, 1f/smoothing);
但實際上我不太確定這是否能滿足您的期望,因為這不是絕對值,但是您稍后會添加每一幀,因此無論如何在其上使用Lerp
對我來說沒有多大意義......我可能會直接使用Lerp
用於將當前mouseLoock
移向新的目標值。
最后你做
mouseLook += smoothV;
if(mouseLook.y>-40 && mouseLook.y<60)
transform.localRotation = Quaternion.AngleAxis (-mouseLook.y, Vector3.right);
character.GetComponent<CharacterController>().transform.localRotation = Quaternion.AngleAxis (mouseLook.x, character.transform.up);
這更新了兩個旋轉。 您的代碼中根本沒有分配任何新位置......
除了GetComponent
的幀明智使用效率極低之外,您應該將該引用存儲一次(例如在Start
)並在以后重用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.