CinemachineCameraOffset.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using UnityEngine;
  2. using Cinemachine.Utility;
  3. using Cinemachine;
  4. /// <summary>
  5. /// An add-on module for Cinemachine Virtual Camera that adds a final offset to the camera
  6. /// </summary>
  7. [AddComponentMenu("")] // Hide in menu
  8. #if UNITY_2018_3_OR_NEWER
  9. [ExecuteAlways]
  10. #else
  11. [ExecuteInEditMode]
  12. #endif
  13. [HelpURL(Documentation.BaseURL + "api/Cinemachine.CinemachineCameraOffset.html")]
  14. [SaveDuringPlay]
  15. public class CinemachineCameraOffset : CinemachineExtension
  16. {
  17. /// <summary>
  18. /// Offset the camera's position by this much (camera space)
  19. /// </summary>
  20. [Tooltip("Offset the camera's position by this much (camera space)")]
  21. public Vector3 m_Offset = Vector3.zero;
  22. /// <summary>
  23. /// When to apply the offset
  24. /// </summary>
  25. [Tooltip("When to apply the offset")]
  26. public CinemachineCore.Stage m_ApplyAfter = CinemachineCore.Stage.Aim;
  27. /// <summary>
  28. /// If applying offset after aim, re-adjust the aim to preserve the screen position
  29. /// of the LookAt target as much as possible
  30. /// </summary>
  31. [Tooltip("If applying offset after aim, re-adjust the aim to preserve the screen position"
  32. + " of the LookAt target as much as possible")]
  33. public bool m_PreserveComposition;
  34. /// <summary>
  35. /// Applies the specified offset to the camera state
  36. /// </summary>
  37. /// <param name="vcam">The virtual camera being processed</param>
  38. /// <param name="stage">The current pipeline stage</param>
  39. /// <param name="state">The current virtual camera state</param>
  40. /// <param name="deltaTime">The current applicable deltaTime</param>
  41. protected override void PostPipelineStageCallback(
  42. CinemachineVirtualCameraBase vcam,
  43. CinemachineCore.Stage stage, ref CameraState state, float deltaTime)
  44. {
  45. if (stage == m_ApplyAfter)
  46. {
  47. bool preserveAim = m_PreserveComposition
  48. && state.HasLookAt && stage > CinemachineCore.Stage.Body;
  49. Vector3 screenOffset = Vector2.zero;
  50. if (preserveAim)
  51. {
  52. screenOffset = state.RawOrientation.GetCameraRotationToTarget(
  53. state.ReferenceLookAt - state.CorrectedPosition, state.ReferenceUp);
  54. }
  55. Vector3 offset = state.RawOrientation * m_Offset;
  56. state.PositionCorrection += offset;
  57. if (!preserveAim)
  58. state.ReferenceLookAt += offset;
  59. else
  60. {
  61. var q = Quaternion.LookRotation(
  62. state.ReferenceLookAt - state.CorrectedPosition, state.ReferenceUp);
  63. q = q.ApplyCameraRotation(-screenOffset, state.ReferenceUp);
  64. state.RawOrientation = q;
  65. }
  66. }
  67. }
  68. }