Laser Beam C# Line Renderer

Hey guys,

Looking to create a laser turret that fires a laser when you hit the trigger. I want to use the LineRenderer to accomplish this. I’m just having troubles making it fire using code. I want there to be nothing on screen until I hit a trigger then it fires a laser out from the turret to a set location (just out of bounds of the screen for example, so I would just hardcode that later).

My assumption is that I make an empty GameObject and place it in front of the turret and then write a script and place it on that.

What I thought might work would be gameObject.AddComponent(LineRenderer); But not sure if that will quite do it, and if it does how to set distances and width and maybe even a falloff?

Thanks,

Tyler

You can just have a LineRenderer component on your laser turret, and in the Start() section, set it’s # of vertices to 0. When you want the laser to be visible, set it’s vertices to 2, and then set the start and end positions.

I’m trying what you suggested but it doesn’t seem to be working, I might be doing the logic wrong. I’ll show what I have thus far.

In my trigger code (so if the right bumper is hit) I have this.

lineRenderer.SetVertexCount(lengthOfLineRenderer);
lineRenderer.SetPosition(1, startPos);
lineRenderer.SetWidth(0.5f, 0.5f);
lineRenderer.SetPosition(2, endPos);

startPos is set to a Vector3(0,0,0) just to test, and endPos is set to a Vector3(50,0,0) just to test as well. Am I doing it wrong?

Well aside from the obvious question of “is lengthOfLineRenderer and int that is 2?” you need to know that LineRenderer is basically an array of vertices, which I’m guessing is your problem. You’re trying to change position of vertices 1 and 2, when you need to be trying to change 0 and 1. The first element of an array always has an index of 0, not one.

Yeah I made it an int of 2, I figured that out. And yeah I realized after working away at it that it was an array and that I was doing it wrong. I’ve got it shooting out now, it’s just getting it to delete itself after a few seconds is a little tricky. Trying to get it to delete itself from the turret to the end point… Kind of like fading away. So right now it’s always there, I shoot once and it stays there.

Well not sure exactly how you want it to look, but if you want it to “fade” away I guess it would just be a matter of lerping/tweening the alpha value of the material you’re using for the LineRenderer. If you want it to appear like it’s a projectile and the tail end of it moves to the target after its done firing, just lerp/tween that vertex’s position from start to end, then set number of verts to 0 to “hide” the laser again.