首先進入場景中,把攝像機掛載到人物主角的下方,先作爲主角的一個子物體存在,然後新建一個腳本CameraFllow,用於控制攝像機跟隨,然後把這個腳本掛載攝像機上面,打開腳本,並複製以下的代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFllow : MonoBehaviour {
//攝像機
private Transform m_Transform;
//人物主角
private Transform player_Transform;
private Vector3 offset;
void Start()
{
m_Transform = gameObject.GetComponent<Transform>();
player_Transform = GameObject.Find("Necromancer").GetComponent<Transform>();
//offset是攝像機相對於人物主角的相對位置
offset = new Vector3(5.7f, 14.6f, -5.2f);
}
void Update()
{
//直接改變攝像機的位置(這種方式比較生硬,建議使用下一種插值的方式)
//m_Transform.position = player_Transform.position + offset;
//插值的方式控制攝像機的跟隨
m_Transform.position = Vector3.Lerp(m_Transform.position, player_Transform.position + offset, Time.deltaTime * 2);
}
}
腳本中的offset就是攝像機相對於人物主角的局部座標,然後把自己場景中的攝像機局部座標複製給Vector3變量offset的x、y、z,操作完成保存腳本。
回到場景中,把攝像機脫離主角,作爲世界座標系進行存在,不需要掛載到任何物體下面,不需要作爲任何物體的子物體進行存在。
運行遊戲,當主角進行移動的時候,攝像機也會跟隨進行移動!