Unity3D中攝像機跟隨方法
using System.Collections;
/// <summary>
/// Camera move.
/// 掛載物件:攝像機
/// 作用:攝像機跟隨人物
/// </summary>
public class CameraMove : MonoBehaviour
{
//攝像機的移動速度
public float moveSpeed = 3f;
//攝像機的旋轉速度
public float turnSpeed = 10f;
//定義私有玩家
private Transform m_Player;
//攝像機與玩家之間的初始偏移量
private Vector3 offset;
//射線的碰撞資訊
private RaycastHit hit;
//攝像機與玩家之間的距離
private float distance;
//攝像機的觀察點
private Vector3[] currentPoints;
//通過Awake拿到自身的元件
void Awake ()
{
//通過tag找到人物元件
m_Player = GameObject.FindWithTag (TagsScript.Player).transform;
//定義一個v3型別的陣列,裡面有5個元素
currentPoints = new Vector3[5];
}
//初始化遊戲物件
void Start ()
{
//遊戲開始時攝像機與玩家之間的距離
distance = Vector3.Distance (transform.position, m_Player.position);
//攝像機指向玩家
//玩家與攝像機之間的偏移量
offset = m_Player.position - transform.position;
}
//物理引擎相關的放到FixedUpdate中
//LateUpdate可以避免卡頓
void LateUpdate ()
{
//攝像機觀察的第一個點
Vector3 startPosition = m_Player.position - offset;
//攝像機的最後一個點
Vector3 endPosition = m_Player.position + Vector3.up * distance;
//把攝像機的五個觀察點放到陣列中,並且1,2,3三個觀察點使用線性插值讓攝像機平滑移動Slerp
currentPoints [1] = Vector3.Slerp (startPosition, endPosition, 0.25f);
currentPoints [2] = Vector3.Slerp (startPosition, endPosition, 0.5f);
currentPoints [3] = Vector3.Slerp (startPosition, endPosition, 0.75f);
currentPoints [0] = startPosition;
currentPoints [4] = endPosition;
//定義一個變數用來儲存固定幀可以看到玩家的觀察點
//viewposition = currentPoints [0]
Vector3 viewposition = currentPoints [0];
//for迴圈遍歷這些點,如果找到最合適的點就把那個當前點賦值給可以看到玩家的觀察點CheckView檢測某個點能否看到玩家
for (int i = 0; i < currentPoints.Length; i++) {
//如果檢測到某個點可以看到玩家
if (CheckView (currentPoints [i])) {
//把這個當前點賦值給viewposition
viewposition = currentPoints [i];
//之後返回不在繼續遍歷
break;
}
}
//把攝像機移動到觀察點
transform.position = Vector3.Lerp (transform.position, viewposition, Time.deltaTime * moveSpeed);
//呼叫攝像機旋轉方法
SmoothRotate ();
}
/// <summary>
/// Checks the view.
/// 檢測某個點是否可以看到玩家
/// </summary>
/// <returns><c>true</c>, if view was checked, <c>false</c> otherwise.</returns>
/// <param name="pos">Position.</param>
//檢測某個點能否看到玩家的方法bool型別
bool CheckView (Vector3 pos)
{
//定義玩家與觀察點之間的方向向量
Vector3 dir = m_Player.position - pos;
//發射射線
if (Physics.Raycast (pos, dir, out hit)) {
//如果射線打到玩家
if (hit.collider.tag == TagsScript.Player) {
//返回true
return true;
}
}
//不然返回false
return false;
}
/// <summary>
/// Smooths the rotate.
/// 攝像機旋轉的方法
/// </summary>
/// 攝像機旋轉的方法
void SmoothRotate ()
{
//指向起始位置
//攝像機到玩家的向量
Vector3 m_Dir = m_Player.position - transform.position;
//要旋轉的角度
Quaternion qua = Quaternion.LookRotation (m_Dir);
transform.rotation = Quaternion.Lerp (transform.rotation, qua, Time.deltaTime * turnSpeed);
//把攝像機x,y軸鎖死
transform.eulerAngles = new Vector3 (transform.eulerAngles.x, 0, 0);
}
}