TheLetterM

Refraction: Laser Emitter

May 11th, 2023
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.30 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class LaserEmitter : MonoBehaviour
  6. {
  7.     private LineRenderer lr;
  8.     public float laserSize = 0.1f;
  9.     [Header("Transforms")]
  10.     public Transform LaserHit;
  11.     public Transform emitPoint;
  12.     public Transform endPoint;
  13.  
  14.     public GameObject sparks;
  15.  
  16.  
  17.     void Start()
  18.     {
  19.         lr = GetComponent<LineRenderer>();
  20.     }
  21.  
  22.     // Update is called once per frame
  23.     void Update()
  24.     {
  25.         lr.startWidth = laserSize;
  26.         lr.endWidth = laserSize; // Allows me to easily and precisely change width of laser in inspector without dragging points
  27.  
  28.         lr.SetPosition(0, emitPoint.position); // Sets beginning of laser to empty gameObject EmitPoint
  29.         RaycastHit hit;
  30.         // public static int RaycastNonAlloc(Vector3 origin, Vector3 direction, RaycastHit[] results, [Internal.DefaultValue("Mathf.Infinity")] float maxDistance, [Internal.DefaultValue("DefaultRaycastLayers")] int layerMask, QueryTriggerInteraction queryTriggerInteraction)
  31.         if (Physics.Raycast(emitPoint.position, transform.right, out hit, Mathf.Infinity, -1, QueryTriggerInteraction.Ignore)) // Laser does not ignore regular colliders, but ignores triggers
  32.         {
  33.  
  34.             if (hit.collider)
  35.             {
  36.                 lr.SetPosition(1, hit.point); // Sets end of laser to point of collision of raycast
  37.                 endPoint.position = hit.point; // Places endPoint gameObject at end of laser
  38.  
  39.                 if (hit.collider.tag == "Reflector" || hit.collider.tag == "Player") // Check if collider hit is reflective OR player
  40.                 {
  41.                     sparks.SetActive(false); // Disables sparks on reflective objects
  42.                 }
  43.                 else
  44.                 {
  45.                     sparks.SetActive(true); // Otherwise, re-enable sparks
  46.                 }
  47.             }
  48.         }
  49.         else
  50.         {
  51.             lr.SetPosition(1, emitPoint.position + transform.right * 100); // If there is no collider in raycast, extend line for 100 units
  52.             // emitPoint.position is added transform.right to make x and y-coordinate of both points of LineRenderer be the same
  53.             endPoint.position = lr.GetPosition(1);
  54.             sparks.SetActive(true);
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment