CurvedUILaserBeam.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 CollideWithMyLayerOnly = false;
  19. [SerializeField]
  20. bool hideWhenNotAimingAtCanvas = false;
  21. #pragma warning restore 0649
  22. // Update is called once per frame
  23. protected void Update()
  24. {
  25. //get direction of the controller
  26. Ray myRay = new Ray(this.transform.position, this.transform.forward);
  27. //make laser beam hit stuff it points at.
  28. if(LaserBeamTransform && LaserBeamDot) {
  29. //change the laser's length depending on where it hits
  30. float length = 10000;
  31. //create layerMaskwe're going to use for raycasting
  32. int myLayerMask = -1;
  33. if (CollideWithMyLayerOnly)
  34. {
  35. //lm with my own layer only.
  36. myLayerMask = 1 << this.gameObject.layer;
  37. }
  38. RaycastHit hit;
  39. if (Physics.Raycast(myRay, out hit, length, myLayerMask))
  40. {
  41. length = Vector3.Distance(hit.point, this.transform.position);
  42. //Find if we hit a canvas
  43. CurvedUISettings cuiSettings = hit.collider.GetComponentInParent<CurvedUISettings>();
  44. if (cuiSettings != null)
  45. {
  46. //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)
  47. int selectablesUnderPointer = cuiSettings.GetObjectsUnderPointer().FindAll(x => x != null && x.GetComponent<Graphic>() != null && x.GetComponent<Graphic>().depth != -1).Count;
  48. length = selectablesUnderPointer == 0 ? 10000 : Vector3.Distance(hit.point, this.transform.position);
  49. }
  50. else if (hideWhenNotAimingAtCanvas) length = 0;
  51. }
  52. else if (hideWhenNotAimingAtCanvas) length = 0;
  53. //set the leangth of the beam
  54. LaserBeamTransform.localScale = LaserBeamTransform.localScale.ModifyZ(length);
  55. }
  56. }
  57. }
  58. }