using System.Collections; using System.Collections.Generic; using UnityEngine; public class SmoothFollow : MonoBehaviour { public Transform target; // 設定跟隨的目標 public float distance = 2.5f; // 設定跟隨的距離 public float height = 1.0f; // 設定目標的高度落差 public float rotationDamping = 1.0f; // 設定跟隨的轉動阻尼 public float heightDamping = 1.0f; // 設定跟隨的高度阻尼 void LateUpdate() { if (!target) return; var wantedRotationAngle = target.eulerAngles.y; // 計算目前的轉動角度 var wantedHeight = target.position.y + height; var currentRotationAngle = transform.eulerAngles.y; var currentHeight = transform.position.y; currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime); currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime); var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0); // Convert the angle into a rotation transform.position = target.position; // Set the position of the camera on the x-z plane to distance meters behind the target transform.position -= currentRotation * Vector3.forward * distance; transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z); transform.LookAt(target); // 保持注視目標物件 } }