How Do I Stop A Line Render From Going Though Gameobject?

How do I stop a line render from going though gameobject such as a box for example… the line render is going through the gameobject. i want it to not because i’m making a laser

I made a quick test to see if I could come up with an answer, and here’s a basic script I wrote you can use as a reference:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LaserCollisionDetection : MonoBehaviour {
    LineRenderer lr;
    // Use this for initialization
    void Start () {
        lr = GetComponent<LineRenderer> ();
    }
   
    // Update is called once per frame
    void Update () {
        //Set up a ray, and make it's direction go forward
        Ray laserRay = new Ray (transform.position,transform.forward);
        RaycastHit colliderInfo;
        //Make sure the first line renderer position is wherever the origin should be, like the barrel of the gun, or whatever. In this case, it's the transform.position
        lr.SetPosition (0, transform.position);
        //If our ray hits something, we want to set the next index of the line renderer to be the exact vector3 where the ray hit, which you can get by
        if (Physics.Raycast (laserRay, out colliderInfo,Mathf.Infinity)) {
            lr.SetPosition (1, colliderInfo.point);
        }
    }

}

I tried to include comments to describe this short process, and there might be a better way, but this is how I’d do it.
In short, use a raycast, and set the positions of the line renderer accordingly to what that raycast hits.

Hope it helps. Let me know if you have any questions.

1 Like