1. 程式人生 > 實用技巧 >Unity 3D裡相機的平滑跟隨(轉)

Unity 3D裡相機的平滑跟隨(轉)

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 public class MoveCamera : MonoBehaviour
 5 {
 6     public float distance = 10.0f;//目標物體與攝像機之間在世界座標基礎上保持水平上的距離
 7     public float height = 5.0f;//攝像機與目標物體之間的高度差
 8     public float heightDamping = 2.0f;//高度變化阻尼
 9     public
float rotationDamping = 3.0f;//旋轉變化阻尼 10 public float offsetHeight = 1.0f;//在攝像機採用lookAt()方法時讓他關注的座標向上偏移1個單位 11 Transform selfTransform;//定義一個對自身的引用 12 public Transform Target;//目標物體引用 13 [AddComponentMenu("Camera-Control/Smooth Follow")] 14 void Start() 15 { 16 selfTransform = GetComponent<Transform>();//
獲得自身的元件資訊 17 } 18 void LateUpdate() 19 {//使用這個更新方法就是保證每幀重新整理時,物體先變化,然後攝像機才跟隨的 20 if (!Target) 21 return;//安全保護 22 float wantedRotationAngle = Target.eulerAngles.y;//目標物體的角度 23 float wantedHeight = Target.position.y + height;//目標物體的高度 24 float currentRotationAngle = selfTransform.eulerAngles.y;//
當前攝像機的角度 25 float currentHeight = selfTransform.position.y;//當前攝像機的高度 26 currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);//執行每一幀時為達到平滑變化的目的,採用線性插值方法每次變化一點 27 currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);//如上 28 Quaternion currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);//因為旋轉角的變化不好用具體的變化角度表示,而四元數剛好可以表示角度繞哪個軸旋轉多少度,表示角度的變化值 29 selfTransform.position = Target.position;//這一步是整個跟隨演算法核心的步驟,目的是將目標物體的世界座標位置付給攝像機,如此攝像機的位置就和目標位置重疊,此時只需要根據上面儲存的攝像機的位置資訊,恢復攝像機的應有位置即可。再次注意,此處改變只是世界座標的position改變,並沒有涉及攝像機自身的鏡頭朝向,及旋轉。所以說可以利用上面記錄的旋轉角的變化量(四元數)來處理攝像機的變化。 30 selfTransform.position -= currentRotation * Vector3.forward * distance;//攝像機此時的位置引數減去角度變化的四元數乘以水平偏移量的積,如此就可以得出攝像機在目標物體後方的位置及狀態。 31 Vector3 currentPosition = transform.position;//把上面已變化一部分的攝像機位置資訊暫存下來 32 currentPosition.y = currentHeight;//改變高度 33 selfTransform.position = currentPosition;//改變過的資訊給攝像機 34 selfTransform.LookAt(Target.position + new Vector3(0, offsetHeight, 0));//使攝像機關注目標物體的座標中心且是用攝像機的本地座標,另外需要注意的是,攝像機關注的是物體本地座標的z軸方向 35 } 36 }