using UnityEngine; namespace Comp { public class CameraFollow : MonoBehaviour { public Transform target; // 跟随目标 public float followSpeed = 2f; // 跟随速度 private Vector3 offset; // 摄像机与目标的距离 public void SetTarget(Transform target) { this.target = target; offset = transform.position - target.position; // 计算摄像机与目标的距离 } private void LateUpdate() { if (target) { Vector3 targetPos = target.position + offset; // 计算目标的位置 targetPos.y = transform.position.y; // y轴不移动 transform.position = Vector3.Lerp(transform.position, targetPos, followSpeed * Time.deltaTime); // 让摄像机缓慢移动到目标位置 } } } }