ResetOriginToCameraOnLoad.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // /******************************************************************************
  2. // * File: ResetOriginToCameraOnLoad.cs
  3. // * Copyright (c) 2023 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
  4. // *
  5. // *
  6. // ******************************************************************************/
  7. #if UNITY_AR_FOUNDATION_LEGACY
  8. using UnityEngine.XR.ARFoundation;
  9. #endif
  10. using Unity.XR.CoreUtils;
  11. using UnityEngine;
  12. namespace QCHT.Samples.Menu
  13. {
  14. public class ResetOriginToCameraOnLoad : MonoBehaviour
  15. {
  16. public bool ResetSessionOriginOnStart = true;
  17. private bool _isSessionOriginMoved;
  18. #if UNITY_AR_FOUNDATION_LEGACY
  19. private ARSessionOrigin _arOrigin;
  20. #endif
  21. private XROrigin _xrOrigin;
  22. private void Awake()
  23. {
  24. #if UNITY_AR_FOUNDATION_LEGACY
  25. _arOrigin = GetComponent<ARSessionOrigin>();
  26. #endif
  27. _xrOrigin = GetComponent<XROrigin>();
  28. }
  29. private void OnEnable() => OffsetSessionOrigin();
  30. private void Update()
  31. {
  32. var cameraInOriginSpaces = Vector3.zero;
  33. var isSet = false;
  34. #if UNITY_AR_FOUNDATION_LEGACY
  35. if (_arOrigin != null)
  36. {
  37. cameraInOriginSpaces = _arOrigin.transform.InverseTransformPoint(_arOrigin.camera.transform.position);
  38. isSet = true;
  39. }
  40. #endif
  41. if (!isSet && _xrOrigin != null)
  42. cameraInOriginSpaces = _xrOrigin.CameraInOriginSpacePos;
  43. if (ResetSessionOriginOnStart && !_isSessionOriginMoved && cameraInOriginSpaces != Vector3.zero)
  44. {
  45. OffsetSessionOrigin();
  46. _isSessionOriginMoved = true;
  47. }
  48. }
  49. public void Recenter()
  50. {
  51. _isSessionOriginMoved = false;
  52. }
  53. private void OffsetSessionOrigin()
  54. {
  55. Transform sessionOrigin = null;
  56. Transform cameraTransform = null;
  57. #if UNITY_AR_FOUNDATION_LEGACY
  58. if (_arOrigin != null)
  59. {
  60. sessionOrigin = _arOrigin.transform;
  61. cameraTransform = _arOrigin.camera.transform;
  62. }
  63. #endif
  64. if (sessionOrigin == null && _xrOrigin != null)
  65. {
  66. sessionOrigin = _xrOrigin.Origin.transform;
  67. cameraTransform = _xrOrigin.Camera.transform;
  68. }
  69. if (sessionOrigin != null && cameraTransform != null)
  70. {
  71. var t = sessionOrigin.transform;
  72. t.Rotate(0.0f, -cameraTransform.rotation.eulerAngles.y, 0.0f, Space.World);
  73. t.position -= cameraTransform.position;
  74. }
  75. }
  76. }
  77. }