LaserBeam.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using UdonSharp;
  2. using UnityEngine;
  3. using VRC.SDKBase;
  4. using VRC.Udon;
  5. using System;
  6. [DisallowMultipleComponent]
  7. [AddComponentMenu("Artyom Scripting System/Laser Beam Controller")]
  8. public class LaserBeam : UdonSharpBehaviour
  9. {
  10. public LineRenderer lineRenderer; // Line Renderer for the laser beam
  11. public Transform laserOrigin; // Origin point of the laser
  12. public float maxDistance = 100.0f; // Maximum distance the laser can reach
  13. public LayerMask layerMask; // Layer mask to specify which colliders to detect
  14. public GameObject endPointObject; // GameObject to place at the end of the laser line
  15. void Update()
  16. {
  17. if (lineRenderer == null || laserOrigin == null)
  18. {
  19. return;
  20. }
  21. RaycastHit hit;
  22. Vector3 laserEndPoint = laserOrigin.position + (laserOrigin.forward * maxDistance);
  23. if (Physics.Raycast(laserOrigin.position, laserOrigin.forward, out hit, maxDistance, layerMask))
  24. {
  25. laserEndPoint = hit.point;
  26. }
  27. // Convert world positions to local positions relative to the laser object's transform
  28. Vector3 localLaserOrigin = transform.InverseTransformPoint(laserOrigin.position);
  29. Vector3 localLaserEndPoint = transform.InverseTransformPoint(laserEndPoint);
  30. lineRenderer.SetPosition(0, localLaserOrigin);
  31. lineRenderer.SetPosition(1, localLaserEndPoint);
  32. // Place the endPointObject at the end of the laser line
  33. if (endPointObject != null)
  34. {
  35. endPointObject.transform.position = laserEndPoint;
  36. }
  37. }
  38. }