I am a beginner in Unity.
So I have implemented the following script with the help of some tutorials to create a laser using line renderer and raycasting. The laser comes in fine but the reflection is confusing and is happening but the direction that it takes I cant understand. If someone could help it shall be great!!
I have the following questions-
-
Does this code look correct for my required application?
-
The reflections I am getting are pretty random and are not along the surface normals. Could there be something during modelling that could be causing this incorrect surface reflections?
-
Using LaserLine.SetPosition (NumOfVert, pos); after the second vector onwards reduces the width of my laser, what could be the reason for this? But if i dont use that the laser still reflects but i dont know in what direction and based on what criteria, BUT its width remains
using UnityEngine; using System; using System.Collections; public class LaserTip_LaserScript : MonoBehaviour { int NumOfVert; LineRenderer LaserLine; Light FlareLight; Ray LaserRay; float LaserWidth= 0.05f; void Start () { LaserLine = gameObject.GetComponent<LineRenderer> (); LaserLine.enabled = false; FlareLight= gameObject.GetComponent<Light> (); FlareLight.enabled = false; } // Update is called once per frame void Update () { if( Input.GetButtonDown("Fire1") ) { LaserLine.SetWidth (LaserWidth, LaserWidth); NumOfVert = 1; LaserRay= new Ray( transform.position, transform.forward); StopCoroutine("FireLaser"); StartCoroutine("FireLaser"); } } IEnumerator FireLaser() { LaserLine.enabled= true; FlareLight.enabled = true; LaserLine.SetPosition(0, LaserRay.origin); while( Input.GetButton("Fire1")){ RaycastHit LaserRayHit; if (Physics.Raycast (LaserRay, out LaserRayHit, 1000)) { LaserLine.SetPosition (NumOfVert, LaserRayHit.point); NumOfVert++; print (NumOfVert); while(LaserRayHit.collider.tag == "MirrorCollider") { //Debug.DrawRay(LaserRayHit.point, LaserRayHit.normal * 10, Color.green); LaserLine.SetVertexCount (NumOfVert); NumOfVert++; Vector3 pos = Vector3.Reflect (LaserRay.direction, LaserRayHit.normal); LaserLine.SetPosition (NumOfVert, pos); LaserRay= new Ray( LaserRayHit.point, LaserRayHit.normal); Physics.Raycast (LaserRay, out LaserRayHit, 1000); } //} } NumOfVert = 1; yield return null; } LaserLine.enabled= false; FlareLight.enabled = false; } }