CameraFollow.cs 902 B

123456789101112131415161718192021222324252627282930
  1. using UnityEngine;
  2. namespace Comp
  3. {
  4. public class CameraFollow : MonoBehaviour
  5. {
  6. public Transform target; // 跟随目标
  7. public float followSpeed = 2f; // 跟随速度
  8. private Vector3 offset; // 摄像机与目标的距离
  9. public void SetTarget(Transform target)
  10. {
  11. this.target = target;
  12. offset = transform.position - target.position; // 计算摄像机与目标的距离
  13. }
  14. private void LateUpdate()
  15. {
  16. if (target)
  17. {
  18. Vector3 targetPos = target.position + offset; // 计算目标的位置
  19. targetPos.y = transform.position.y; // y轴不移动
  20. transform.position =
  21. Vector3.Lerp(transform.position, targetPos, followSpeed * Time.deltaTime); // 让摄像机缓慢移动到目标位置
  22. }
  23. }
  24. }
  25. }