Unlimited WordPress themes, graphics, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Game Development
  2. Game Art Effects

How to Generate Shockingly Good 2D Lightning Effects in Unity (JavaScript)

Read Time:35 minsLanguages:

There are plenty of uses for lightning effects in games, from background ambiance during a storm to the devastating lightning attacks of a sorcerer. In this tutorial, I'll explain how to programmatically generate awesome 2D lightning effects: bolts, branches, and even text.

This tutorial is written specifically for Unity, with all code snippets in JavaScript. The same tutorial is also available with C# code. If you don't use Unity, take a look at this platform-agnostic version of the same tutorial; it's written for XNA, but you should be able to use the same techniques and concepts in any gamedev engine and platform.


Check out the demo below:

Click the Unity object, then use the number keys to switch between demos. Some demos require you to click in one or two locations to activate them.

Basic Setup

To get started, you'll need to create a new 2D project in Unity. Name it whatever you'd like. In Unity, create four folders: Materials, Prefabs, Scripts, and Sprites.

Next, click the Main Camera and make sure that its Projection is set to Orthographic. Set the camera's Size to 10.

Right-click on the Materials folder and select Create > Material. Rename it to Additive. Select this material and change its Shader to Particles > Additive. This will help your lightning "pop" later on.

Step 1: Draw a Glowing Line

The basic building block we need to make lightning from is a line segment. Start by opening your favourite image editing software and drawing a straight line of lightning with a glow effect. Here's what mine looks like:

We want to draw lines of different lengths, so we will cut the line segment into three pieces as shown below (crop your image as necessary). This will allow us to stretch the middle segment to any length we like. Since we are going to be stretching the middle segment, we can save it as only a single pixel thick. Also, as the left and right pieces are mirror images of each other, we only need to save one of them; we can flip it in the code.

Drag your image files onto the Sprites folder in the Project panel. This will import the image files into the Unity project. Click on the sprites to view them in the Inspector panel. Make sure the Texture Type is set to Sprite(2D \ uGUI), and set the Packing Tag to Line.

The Packing Tag will help Unity save on draw calls when drawing our lightning, so make sure you give both sprites the same Packing Tag or else it won't improve performance.

Now, let's declare a new class to handle drawing line segments:

A and B are the line's endpoints. By scaling and rotating the pieces of the line, we can draw a line of any thickness, length, and orientation.

Add the following Draw() method to the bottom of the LineJS class:

The way we position the middle segment and the caps will make them join seamlessly when we draw them. The start cap is positioned at point A, the middle segment is stretched to the desired width, and the end cap is rotated 180° and drawn at point B.

Now we need to create a prefab for our LineJS class to work with. In Unity, from the menu, select GameObject > Create Empty. The object will appear in your Hierarchy panel. Rename it to LineJS and drag your LineJS script onto it. It should look something like the image below.

We'll use this object as a container for the pieces of our line segment.

Now we need to create objects for the pieces of our line segment. Create three Sprites by selecting GameObject > Create Other > Sprite from the menu. Rename them toStartCap, MiddleSegment, and EndCap. Drag them onto our LineJS object so that they become its children—this should look something like the image below.

Go through each child and set its Material in the Sprite Renderer to the Additive material we created earlier. Assign each child the appropriate sprite. (The two caps should get the cap sprite and the middle segment should get the line sprite.)

Click on the LineJS object so that you can see the script in the Inspector panel. Assign the children to their appropriate slots and then drag the LineJS object into the Prefabs folder to create a prefab for it. You can now delete the LineJS object from the Hierarchy panel.

Step 2: Create Jagged Lines

Lightning tends to form jagged lines, so we'll need an algorithm to generate these. We'll do this by picking points at random along a line, and displacing them a random distance from the line.

Using a completely random displacement tends to make the line too jagged, so we'll smooth the results by limiting how far from each other neighbouring points can be displaced—see the difference between the second and third lines in the figure below.

We smooth the line by placing points at a similar offset to the previous point; this allows the line as a whole to wander up and down, while preventing any part of it from being too jagged.

Let's create a LightningBoltJS class to handle creating our jagged lines.

The code may look a bit intimidating, but it's not so bad once you understand the logic. Before we continue on, understand that we've chosen to pool our line segments in the bolts (since constantly instantiating and destroying objects can be costly in Unity).

  • The Initialize() function will be called once on each lightning bolt and will determine how many line segments each bolt is allowed to use.
  • The activateLine() function will activate a line segment using the given position data.
  • The DeactivateSegments() function will deactivate any active line segments in our bolt.
  • The ActivateBolt() function will handle creating our jagged lines and will call the activateLine() function to activate our line segments at the appropriate positions.

To create our jagged lines, we start by computing the slope between our two points, as well as the normal vector to that slope. We then choose a number of random positions along the line and store them in our positions list. We scale these positions between 0 and 1, such that 0 represents the start of the line and 1 represents the end point., and then sort these positions to allow us to easily add line segments between them.

The loop goes through the randomly chosen points and displaces them along the normal by a random amount. The scale factor is there to avoid overly sharp angles, and theenvelope ensures the lightning actually goes to the destination point by limiting displacement when we're close to the end. The spread is to assist in controlling how far the segments deviate from the slope of our line; a spread of 0 will essentially give you a straight line.

So, like we did with our LineJS class, let's make this into a prefab. From the menu, select GameObject > Create Empty. The object will appear in your Hierarchy panel. Rename it to BoltJS, and drag a copy of the LightningBoltJS script onto it. Finally, click on the BoltJS object and assign the LineJS prefab, from the Prefabs folder, to the appropriate slot in the LightningBoltJS script. Once you're done with that, simply drag the BoltJS object into the Prefabs folder to create a prefab.

Step 3: Add Animation

Lightning should flash brightly and then fade out. This is what our Update() and Draw() functions in LightningBoltJS are for. Calling Update() will make the bolt fade out. Calling Draw() will update the bolt's color on the screen. IsComplete() will tell you when the bolt has fully faded out.

Step 4: Create a Bolt

Now that we have our LightningBoltJS class, let's actually put it to good use and set up a quick demo scene.

We're going to use an object pool for this demo, so we'll want to create an empty object to hold our active and inactive bolts (simply for organizational purposes). In Unity, from the menu, select GameObject > Create Empty. The object will appear in your Hierarchy panel. Rename it to LightningPoolHolder.

Right click on the Scripts folder and select Create > Javascript. Name your script DemoScriptJS and open it. Here's some quick code to get you started:

All this code does is give us a way to create bolts using object pooling. There are other ways you can set this up, but this is what we're going with! Once we've set it up, all you'll have to do is click twice to create a bolt on the screen: once for the start position and once for the end position.

We'll need an object to put our DemoScriptJS on. From the menu, select GameObject > Create Empty. The object will appear in your Hierarchy panel. Rename it to DemoScript and drag your DemoScriptJS script onto it. Click on the DemoScript object so we can view it in the Inspector panel. Assign the BoltJS prefab, from the Prefabs folder, to the matching slot in the DemoScriptJS.

That should be enough to get you going! Run the scene in Unity and try it out!

Step 5: Create Branch Lightning

You can use the LightningBoltJS class as a building block to create more interesting lightning effects. For example, you can make the bolts branch out as shown below:

To make the lightning branch, we pick random points along the lightning bolt and add new bolts that branch out from these points. In the code below, we create between three and six branches which separate from the main bolt at 30° angles.

This code works very similarly to our LightningBoltJS class with the exception that it does not use object pooling. Calling Initialize() is all you will need to do to create a branching bolt; after that, you will just need to call Update() and Draw(). I'll show you exactly how to do this in our DemoScriptJS later on in the tutorial.

You may have noticed the reference to a GetPoint() function in the LightningBoltJS class. We haven't actually implemented that function yet, so let's take care of that now.

Add the following function in the bottom of the LightningBoltJS class:

Step 6: Create Lightning Text

Below is a video of another effect you can make out of the lightning bolts:

We'll need to do a little more setup for this one. First, from the Project panel, select Create > RenderTexture. Rename it to RenderText and set its Size to 256x256px. (It doesn't necessarily have to be that exact size, but the smaller it is, the faster the program will run.)

From the menu, select Edit > Project Settings > Tags and Layers. Then, in the Inspector panel, expand the Layers drop down and add Text into User Layer 8.

We'll then need to create a second camera. From the menu, select GameObject > Create Other > Camera. Rename it to TextCamera, and set its Projection to Orthographic and its Clear Flags to Solid Color. Set its Background color to(R: 0, G: 0, B: 0, A: 0) and set its Culling Mask to only be Text (the layer we just created). Finally, set its Target Texture to RenderText (the RenderTexture we created earlier). You'll probably need to play around with the camera's Size later, in order to get everything to fit on the screen.

Now we'll need to create the actual text we'll be drawing with our lightning. From the menu select GameObject > Create Other > GUI Text. Select the GUI Text object from the Hierarchy panel and set its Text to LIGHTNING, its Anchor to middle center, and its Alignment to center. Then, set its Layer to the Text layer we created earlier. You'll probably have to play around with the Font Size in order to fit the text on the screen.

Now select the Main Camera and set its Culling Mask to be everything but our Text layer. This will cause our GUI Text to apparently disappear from the screen, but it should be drawn on the RenderTexture we created earlier: select RenderText from the Project panel and you should be able to see the word LIGHTNING on the preview on the bottom of the panel.

If you can't see the word LIGHTNING, you'll need to play around with your positioning, font size, and (text) camera size. To help you position your text, click on TextCamera in the Hierarchy panel, and set its Target Texture to None. You'll now be able to see your GUI Text if you center it on the TextCamera. Once you have everything positioned, set the TextCamera's Target Texture back to RenderText.

Now for the code! We'll need to get the pixels from the text that we're drawing. We can do this by drawing our text to a RenderTarget and reading back the pixel data into aTexture2D with Texture2D.ReadPixels(). Then, we can store the coordinates of the pixels from the text as a List.<Vector2>.

Here's the code to do that:

Note: We'll have to run this function as a Coroutine at the start of our program in order for it to run correctly.

After that, each frame, we can randomly pick pairs of these points and create a lightning bolt between them. We want to design it so that the closer two points are to one another, the greater the chance is that we create a bolt between them.

There's a simple technique we can use to accomplish this: we'll pick the first point at random, and then we'll pick a fixed number of other points at random and choose the nearest.

Here's the code for that (we'll add it to our DemoScriptJS later):

The number of candidate points we test will affect the look of the lightning text; checking a larger number of points will allow us to find very close points to draw bolts between, which will make the text very neat and legible, but with fewer long lightning bolts between letters. Smaller numbers will make the lightning text look wilder but less legible.

Step 7: Try Other Variations

We've discussed making branch lightning and lightning text, but those certainly aren't the only effects you can make. Let's look at a couple other variations on lightning you may want to use.

Moving Lightning

You may often want to make a moving bolt of lightning. You can do this by adding a new short bolt each frame at the end point of the previous frame's bolt.

Burst Lightning

This variation offers a dramatic effect that shoots lightning out in a circle from the centre point:

Step 8: Put It All Together in DemoScriptJS

You're going to want to be able to try out all of these fancy effects we've created so far, so let's put all of them into the DemoScriptJS we made earlier. You'll be able to toggle between effects by hitting the number keys on your keyboard to select the effect, and then just clicking twice like we did with our bolts before.

Here's the full code:


Lightning is a great special effect for sprucing up your games. The effects described in this tutorial are a nice starting point, but it's certainly not all you can do with lightning. With a bit of imagination you can make all kinds of awe-inspiring lightning effects! Download the source code and experiment on your own.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.