Cinemachine3rdPersonAim.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #if !UNITY_2019_3_OR_NEWER
  2. #define CINEMACHINE_PHYSICS
  3. #endif
  4. using UnityEngine;
  5. namespace Cinemachine
  6. {
  7. #if CINEMACHINE_PHYSICS
  8. /// <summary>
  9. /// An add-on module for Cinemachine Virtual Camera that forces the LookAt
  10. /// point to the center of the screen, based on the Follow target's orientation,
  11. /// cancelling noise and other corrections.
  12. /// This is useful for third-person style aim cameras that want a dead-accurate
  13. /// aim at all times, even in the presence of positional or rotational noise.
  14. /// </summary>
  15. [AddComponentMenu("")] // Hide in menu
  16. [ExecuteAlways]
  17. [SaveDuringPlay]
  18. [DisallowMultipleComponent]
  19. public class Cinemachine3rdPersonAim : CinemachineExtension
  20. {
  21. /// <summary>Objects on these layers will be detected.</summary>
  22. [Header("Aim Target Detection")]
  23. [Tooltip("Objects on these layers will be detected")]
  24. public LayerMask AimCollisionFilter;
  25. /// <summary>Objects with this tag will be ignored.
  26. /// It is a good idea to set this field to the target's tag.</summary>
  27. [TagField]
  28. [Tooltip("Objects with this tag will be ignored. "
  29. + "It is a good idea to set this field to the target's tag")]
  30. public string IgnoreTag = string.Empty;
  31. /// <summary>How far to project the object detection ray.</summary>
  32. [Tooltip("How far to project the object detection ray")]
  33. public float AimDistance;
  34. /// <summary>This 2D object will be positioned in the game view over the raycast hit point,
  35. /// if any, or will remain in the center of the screen if no hit point is
  36. /// detected. May be null, in which case no on-screen indicator will appear.</summary>
  37. [Tooltip("This 2D object will be positioned in the game view over the raycast hit point, if any, "
  38. + "or will remain in the center of the screen if no hit point is detected. "
  39. + "May be null, in which case no on-screen indicator will appear")]
  40. public RectTransform AimTargetReticle;
  41. private void OnValidate()
  42. {
  43. AimDistance = Mathf.Max(1, AimDistance);
  44. }
  45. private void Reset()
  46. {
  47. AimCollisionFilter = 1;
  48. IgnoreTag = string.Empty;
  49. AimDistance = 200.0f;
  50. AimTargetReticle = null;
  51. }
  52. /// <summary>Notification that this virtual camera is going live.</summary>
  53. /// <param name="fromCam">The camera being deactivated. May be null.</param>
  54. /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param>
  55. /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param>
  56. /// <returns>True to request a vcam update of internal state</returns>
  57. public override bool OnTransitionFromCamera(
  58. ICinemachineCamera fromCam, Vector3 worldUp, float deltaTime)
  59. {
  60. CinemachineCore.CameraUpdatedEvent.RemoveListener(DrawReticle);
  61. CinemachineCore.CameraUpdatedEvent.AddListener(DrawReticle);
  62. return false;
  63. }
  64. void DrawReticle(CinemachineBrain brain)
  65. {
  66. if (!brain.IsLive(VirtualCamera) || brain.OutputCamera == null)
  67. CinemachineCore.CameraUpdatedEvent.RemoveListener(DrawReticle);
  68. else
  69. {
  70. var player = VirtualCamera.Follow;
  71. if (AimTargetReticle != null && player != null)
  72. {
  73. // Adjust for actual player aim target (may be different due to offset)
  74. var playerPos = player.position;
  75. var aimTarget = VirtualCamera.State.ReferenceLookAt;
  76. var dir = aimTarget - playerPos;
  77. if (RuntimeUtility.RaycastIgnoreTag(new Ray(playerPos, dir),
  78. out RaycastHit hitInfo, dir.magnitude, AimCollisionFilter, IgnoreTag))
  79. aimTarget = hitInfo.point;
  80. AimTargetReticle.position = brain.OutputCamera.WorldToScreenPoint(aimTarget);
  81. }
  82. }
  83. }
  84. Vector3 GetLookAtPoint(Vector3 camPos)
  85. {
  86. var aimDistance = AimDistance;
  87. var player = VirtualCamera.Follow;
  88. // We don't want to hit targets behind the player
  89. var fwd = Vector3.forward;
  90. if (player != null)
  91. {
  92. var playerOrientation = player.transform.rotation;
  93. fwd = playerOrientation * Vector3.forward;
  94. var playerPos = Quaternion.Inverse(playerOrientation) * (player.position - camPos);
  95. if (playerPos.z > 0)
  96. {
  97. camPos += fwd * playerPos.z;
  98. aimDistance -= playerPos.z;
  99. }
  100. }
  101. aimDistance = Mathf.Max(1, aimDistance);
  102. bool hasHit = RuntimeUtility.RaycastIgnoreTag(new Ray(camPos, fwd),
  103. out RaycastHit hitInfo, aimDistance, AimCollisionFilter, IgnoreTag);
  104. return hasHit ? hitInfo.point : camPos + fwd * aimDistance;
  105. }
  106. /// <summary>
  107. /// Sets the ReferenceLookAt to be the result of a raycast in the direction of camera forward.
  108. /// If an object is hit, point is placed there, else it is placed at AimDistance.
  109. /// </summary>
  110. /// <param name="vcam">The virtual camera being processed</param>
  111. /// <param name="stage">The current pipeline stage</param>
  112. /// <param name="state">The current virtual camera state</param>
  113. /// <param name="deltaTime">The current applicable deltaTime</param>
  114. protected override void PostPipelineStageCallback(
  115. CinemachineVirtualCameraBase vcam,
  116. CinemachineCore.Stage stage, ref CameraState state, float deltaTime)
  117. {
  118. if (stage == CinemachineCore.Stage.Body)
  119. {
  120. // Raycast to establish what we're actually aiming at
  121. state.ReferenceLookAt = GetLookAtPoint(state.CorrectedPosition);
  122. }
  123. if (stage == CinemachineCore.Stage.Finalize)
  124. {
  125. var dir = state.ReferenceLookAt - state.FinalPosition;
  126. if (dir.sqrMagnitude > 0.01f)
  127. {
  128. state.RawOrientation = Quaternion.LookRotation(dir, state.ReferenceUp);
  129. state.OrientationCorrection = Quaternion.identity;
  130. }
  131. }
  132. }
  133. }
  134. #endif
  135. }