NRLaserVisual.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. namespace NRKernal
  10. {
  11. using UnityEngine;
  12. /// <summary> A nr laser visual. </summary>
  13. public class NRLaserVisual : MonoBehaviour
  14. {
  15. /// <summary> The raycaster. </summary>
  16. [SerializeField]
  17. private NRPointerRaycaster m_Raycaster;
  18. /// <summary> The line renderer. </summary>
  19. [SerializeField]
  20. private LineRenderer m_LineRenderer;
  21. /// <summary> True to show, false to hide the on hit only. </summary>
  22. public bool showOnHitOnly;
  23. /// <summary> The default distance. </summary>
  24. public float defaultDistance = 1.2f;
  25. /// <summary> Awakes this object. </summary>
  26. private void Awake()
  27. {
  28. defaultDistance = Mathf.Clamp(defaultDistance, m_Raycaster.NearDistance, m_Raycaster.FarDistance);
  29. }
  30. /// <summary> Late update. </summary>
  31. protected virtual void LateUpdate()
  32. {
  33. if (!NRInput.LaserVisualActive)
  34. {
  35. m_LineRenderer.enabled = false;
  36. return;
  37. }
  38. var result = m_Raycaster.FirstRaycastResult();
  39. if (showOnHitOnly && !result.isValid)
  40. {
  41. m_LineRenderer.enabled = false;
  42. return;
  43. }
  44. var points = m_Raycaster.BreakPoints;
  45. var pointCount = points.Count;
  46. if (pointCount < 2)
  47. {
  48. return;
  49. }
  50. m_LineRenderer.enabled = true;
  51. m_LineRenderer.useWorldSpace = false;
  52. var startPoint = transform.TransformPoint(0f, 0f, m_Raycaster.NearDistance);
  53. var endPoint = result.isValid ? points[pointCount - 1]
  54. : (m_Raycaster.transform.position + m_Raycaster.transform.forward * defaultDistance);
  55. if (pointCount == 2)
  56. {
  57. #if UNITY_5_6_OR_NEWER
  58. m_LineRenderer.positionCount = 2;
  59. #elif UNITY_5_5_OR_NEWER
  60. lineRenderer.numPositions = 2;
  61. #else
  62. lineRenderer.SetVertexCount(2);
  63. #endif
  64. m_LineRenderer.SetPosition(0, transform.InverseTransformPoint(startPoint));
  65. m_LineRenderer.SetPosition(1, transform.InverseTransformPoint(endPoint));
  66. }
  67. }
  68. /// <summary> Executes the 'disable' action. </summary>
  69. protected virtual void OnDisable()
  70. {
  71. m_LineRenderer.enabled = false;
  72. }
  73. }
  74. }