MoveWithCamera.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. using UnityEngine;
  10. namespace NRKernal.NRExamples
  11. {
  12. public class MoveWithCamera : MonoBehaviour
  13. {
  14. /// <summary> The origin distance. </summary>
  15. private float originDistance;
  16. /// <summary> True to use relative. </summary>
  17. [SerializeField]
  18. private bool useRelative = true;
  19. private Transform m_CenterCamera;
  20. private Transform CenterCamera
  21. {
  22. get
  23. {
  24. if (m_CenterCamera == null)
  25. {
  26. if (NRSessionManager.Instance.CenterCameraAnchor != null)
  27. {
  28. m_CenterCamera = NRSessionManager.Instance.CenterCameraAnchor;
  29. }
  30. else if (Camera.main != null)
  31. {
  32. m_CenterCamera = Camera.main.transform;
  33. }
  34. }
  35. return m_CenterCamera;
  36. }
  37. }
  38. private void Start()
  39. {
  40. originDistance = useRelative ? Vector3.Distance(transform.position, CenterCamera == null ? Vector3.zero : CenterCamera.position) : 0;
  41. }
  42. /// <summary> Late update. </summary>
  43. void LateUpdate()
  44. {
  45. if (CenterCamera != null)
  46. {
  47. transform.position = CenterCamera.transform.position + CenterCamera.transform.forward * originDistance;
  48. transform.rotation = CenterCamera.transform.rotation;
  49. }
  50. }
  51. }
  52. }