CameraFollow.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using UnityEngine;
  2. public class CameraFollow : MonoBehaviour
  3. {
  4. [Header("跟随目标")]
  5. public Transform target;
  6. [Header("跟随参数")]
  7. public float distance = 10f;
  8. public float height = 5f;
  9. public float angle = 45f;
  10. public float smoothSpeed = 5f;
  11. [Header("视角参数")]
  12. public float lookAtHeightOffset = 1f;
  13. private Vector3 currentVelocity;
  14. private void LateUpdate()
  15. {
  16. if (target == null)
  17. {
  18. return;
  19. }
  20. float angleRad = angle * Mathf.Deg2Rad;
  21. float offsetX = -Mathf.Sin(angleRad) * distance;
  22. float offsetZ = -Mathf.Cos(angleRad) * distance;
  23. Vector3 targetPosition = target.position + new Vector3(offsetX, height, offsetZ);
  24. transform.position = Vector3.SmoothDamp(
  25. transform.position,
  26. targetPosition,
  27. ref currentVelocity,
  28. 1f / smoothSpeed
  29. );
  30. Vector3 lookAtPosition = target.position + Vector3.up * lookAtHeightOffset;
  31. transform.LookAt(lookAtPosition);
  32. }
  33. public void SetTarget(Transform newTarget)
  34. {
  35. target = newTarget;
  36. }
  37. public void SetAngle(float newAngle)
  38. {
  39. angle = newAngle;
  40. }
  41. public void SetDistance(float newDistance)
  42. {
  43. distance = newDistance;
  44. }
  45. public void SetHeight(float newHeight)
  46. {
  47. height = newHeight;
  48. }
  49. }