最簡(jiǎn)單的一種就是先設(shè)置好攝像機(jī)跟物體的相對(duì)距離躺涝,在腳本里就可以由物體的位置疗我,跟相對(duì)距離仔夺,就可以求出攝像機(jī)的位置琐脏,用插值的方法可以讓攝像機(jī)平滑跟隨。
原理:攝像機(jī)與player以向量(有大小,有方向)相連日裙,這樣就可以確定攝像機(jī)與player的相對(duì)距離了吹艇,這樣人物走動(dòng),攝像機(jī)也會(huì)跟隨移動(dòng)阅签。
image.png
將下列代碼與camera綁定就可以實(shí)現(xiàn)第三人稱(chēng)攝像機(jī)跟隨掐暮。
public class CameraFollow : MonoBehaviour {
// The position that that camera will be following.
public Transform target;
// The speed with which the camera will be following.
public float smoothing = 5f;
// The initial offset from the target.
Vector3 offset;
void Start() {
// Calculate the initial offset.
offset = transform.position - target.position;
}
void FixedUpdate () {
// Create a postion the camera is aiming for based on the offset from the target.
Vector3 targetCamPos = target.position + offset;
// Smoothly interpolate between the camera's current position and it's target position.
transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
}
}
代碼解釋?zhuān)?br>
Transfrom
image.png
The Transform component determines the Position, Rotation, and Scale of each object in the scene. Every GameObject has a Transform.
變換組件確定場(chǎng)景中每個(gè)對(duì)象的位置蝎抽、旋轉(zhuǎn)和比例政钟。 每個(gè)游戲?qū)ο笥幸粋€(gè)轉(zhuǎn)換。
Vector3
表示定義了一個(gè)三維向量
static function Lerp (from : Vector3, to : Vector3, t : float) : Vector3
image.png
關(guān)于vector3相關(guān)詳細(xì)解釋可查看鏈接http://www.ceeger.com/Script/Vector3/Vector3.html
image.png
FixedUpdate():固定更新事件樟结,執(zhí)行N次养交,0.02秒執(zhí)行一次。所有物理組件相關(guān)的更新都在這個(gè)事件中處理瓢宦。
將場(chǎng)景中的player(攝像機(jī)跟隨的物體)拖入target中場(chǎng)景中的就可以實(shí)現(xiàn)簡(jiǎn)單的第三人稱(chēng)攝像機(jī)跟隨碎连。