CinemachineCameraOffset.cs 2.6 KB

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