Lightning Strike on Unity 3d Using Line renderer.

What do we need to do it?

We need to use unity build in feature called LineRenderer wich draws line between two objects.

We set it to draw line between our 1st person controller and its target in this case red cube in middle. Then we make randomised path to our line.  Then we make loop when we push mouse button 0 aka right mouse click 1st person controller will shoot lightning on red cube. Ofc to make line look like lighting you will have to use texture and change color. I decided to use unitys own textures and selected blue color for my lightning. You can add texture and color from inspector.

 Full code:

var targetObject : GameObject;
private var lineRenderer : LineRenderer;
var asd : int = 3;
function Start()
{

    lineRenderer = GetComponent(LineRenderer);
}

function Update ()
{
//Check if we press right mouse button
	if(Input.GetKey(KeyCode.Mouse0))
	{
//Enables line renderer
		lineRenderer.enabled = true;
 //Sets starting position to players position
			lineRenderer.SetPosition(0,this.transform.localPosition);
//Loop that moves line to "random directions"
	    	for(var i:int=1;i<4;i++)
	    	 {
	        	var pos = Vector3.Lerp(this.transform.localPosition,targetObject.transform.localPosition,i/4.0f);

                        //randomises lines position
	        	pos.x += Random.Range(-0.4f,0.4f);
	        	pos.y += Random.Range(-0.4f,0.4f);

	        	lineRenderer.SetPosition(i,pos);
	   		}
//Lines end postion at the target
	    	lineRenderer.SetPosition(4,targetObject.transform.localPosition);
	}
    else
    {
// If we dont press right mouse button disables linerenderer
    	lineRenderer.enabled = false;

    }
}

Lightning bolt

Based on this tutorial

Leave a comment