LaserBeam.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using UdonSharp;
  2. using UnityEngine;
  3. [UdonBehaviourSyncMode(BehaviourSyncMode.NoVariableSync)]
  4. [DisallowMultipleComponent]
  5. [AddComponentMenu("Artyom Scripting System/Laser Beam Controller")]
  6. public class LaserBeam : UdonSharpBehaviour
  7. {
  8. public LineRenderer lineRenderer; // Line Renderer for the laser beam
  9. public Transform laserOrigin; // Origin point of the laser
  10. public float maxDistance = 100.0f; // Maximum distance the laser can reach
  11. public LayerMask layerMask; // Layer mask to specify which colliders to detect
  12. public GameObject endPointObject; // GameObject to place at the end of the laser line
  13. [Tooltip("Whether the beam stops at trigger colliders, such as a Laser Receiver's trigger.")]
  14. public bool hitTriggers = true;
  15. void Start()
  16. {
  17. // World-space points draw correctly whichever object the Line Renderer is on
  18. if (lineRenderer != null) lineRenderer.useWorldSpace = true;
  19. if (layerMask.value == 0)
  20. Debug.LogWarning("[AUMSS] Laser Beam Controller: Layer Mask is Nothing, so the beam passes through everything.");
  21. }
  22. void Update()
  23. {
  24. if (lineRenderer == null || laserOrigin == null)
  25. {
  26. return;
  27. }
  28. RaycastHit hit;
  29. Vector3 laserEndPoint = laserOrigin.position + (laserOrigin.forward * maxDistance);
  30. QueryTriggerInteraction triggers = hitTriggers ? QueryTriggerInteraction.Collide : QueryTriggerInteraction.Ignore;
  31. if (Physics.Raycast(laserOrigin.position, laserOrigin.forward, out hit, maxDistance, layerMask.value, triggers))
  32. {
  33. laserEndPoint = hit.point;
  34. }
  35. lineRenderer.SetPosition(0, laserOrigin.position);
  36. lineRenderer.SetPosition(1, laserEndPoint);
  37. // Place the endPointObject at the end of the laser line
  38. if (endPointObject != null)
  39. {
  40. endPointObject.transform.position = laserEndPoint;
  41. }
  42. }
  43. }