ThirdPersonFollowDistanceModifier.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using UnityEngine;
  2. namespace Cinemachine.Examples
  3. {
  4. /// <summary>
  5. /// This is an add-on for Cinemachine virtual cameras containing the ThirdPersonFollow component.
  6. /// It modifies the camera distance as a function of vertical angle.
  7. /// </summary>
  8. [SaveDuringPlay]
  9. public class ThirdPersonFollowDistanceModifier : MonoBehaviour
  10. {
  11. [Tooltip("Camera angle that corresponds to the start of the distance graph")]
  12. public float MinAngle;
  13. [Tooltip("Camera angle that corresponds to the end of the distance graph")]
  14. public float MaxAngle;
  15. [Tooltip("Defines how the camera distance scales as a function of vertical camera angle. "
  16. + "X axis of graph go from 0 to 1, Y axis is the multiplier that will be "
  17. + "applied to the base distance.")]
  18. public AnimationCurve DistanceScale;
  19. Cinemachine3rdPersonFollow TpsFollow;
  20. Transform FollowTarget;
  21. float BaseDistance;
  22. void Reset()
  23. {
  24. MinAngle = -90;
  25. MaxAngle = 90;
  26. DistanceScale = AnimationCurve.EaseInOut(0, 0.5f, 1, 2);
  27. }
  28. void OnEnable()
  29. {
  30. var vcam = GetComponentInChildren<CinemachineVirtualCamera>();
  31. if (vcam != null)
  32. {
  33. TpsFollow = vcam.GetCinemachineComponent<Cinemachine3rdPersonFollow>();
  34. FollowTarget = vcam.Follow;
  35. }
  36. // Store the base camera distance, for consistent scaling
  37. if (TpsFollow != null)
  38. BaseDistance = TpsFollow.CameraDistance;
  39. }
  40. void OnDisable()
  41. {
  42. // Restore the TPS base camera distance
  43. if (TpsFollow != null)
  44. TpsFollow.CameraDistance = BaseDistance;
  45. }
  46. void Update()
  47. {
  48. // Scale the TPS camera distance
  49. if (TpsFollow != null && FollowTarget != null)
  50. {
  51. var xRot = FollowTarget.rotation.eulerAngles.x;
  52. if (xRot > 180)
  53. xRot -= 360;
  54. var t = (xRot - MinAngle) / (MaxAngle - MinAngle);
  55. TpsFollow.CameraDistance = BaseDistance * DistanceScale.Evaluate(t);
  56. }
  57. }
  58. }
  59. }