CurvedUILaserBeam.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.EventSystems;
  4. using UnityEngine.UI;
  5. namespace CurvedUI
  6. {
  7. /// <summary>
  8. /// This class contains code that controls the visuals (only!) of the laser pointer.
  9. /// </summary>
  10. public class CurvedUILaserBeam : MonoBehaviour
  11. {
  12. #pragma warning disable 0649
  13. [SerializeField]
  14. Transform LaserBeamTransform;
  15. [SerializeField]
  16. Transform LaserBeamDot;
  17. [SerializeField]
  18. bool hideWhenNotAimingAtCanvas = false;
  19. #pragma warning restore 0649
  20. // Update is called once per frame
  21. protected void Update()
  22. {
  23. //get direction of the controller
  24. Ray myRay = new Ray(this.transform.position, this.transform.forward);
  25. //make laser beam hit stuff it points at.
  26. if(LaserBeamTransform && LaserBeamDot) {
  27. //change the laser's length depending on where it hits
  28. float length = 10000;
  29. RaycastHit hit;
  30. if (Physics.Raycast(myRay, out hit, length, CurvedUIInputModule.Instance.RaycastLayerMask))
  31. {
  32. length = Vector3.Distance(hit.point, this.transform.position);
  33. //Find if we hit a canvas
  34. CurvedUISettings cuiSettings = hit.collider.GetComponentInParent<CurvedUISettings>();
  35. if (cuiSettings != null)
  36. {
  37. //find if there are any canvas objects we're pointing at. we only want transforms with graphics to block the pointer. (that are drawn by canvas => depth not -1)
  38. int selectablesUnderPointer = cuiSettings.GetObjectsUnderPointer().FindAll(x => x != null && x.GetComponent<Graphic>() != null && x.GetComponent<Graphic>().depth != -1).Count;
  39. length = selectablesUnderPointer == 0 ? 10000 : Vector3.Distance(hit.point, this.transform.position);
  40. }
  41. else if (hideWhenNotAimingAtCanvas) length = 0;
  42. }
  43. else if (hideWhenNotAimingAtCanvas) length = 0;
  44. //set the leangth of the beam
  45. LaserBeamTransform.localScale = LaserBeamTransform.localScale.ModifyZ(length);
  46. }
  47. }
  48. }
  49. }