Programming lightning was way too much fun, so it would be silly to not give it a blog entry. Plenty of games have lightning, but the style and quality varies a lot. I wanted mine to be as realistic as possible. Later on, if I don’t think it fits with the style of the game, I can get more artistic with it.
It took a fair amount of fiddling to settle on the best way to render lightning. To make the basic lightning shape I start with a segment between the start and end points, divide it in half to produce two new segments, and displace the center point by a random amount. This process is repeated on new segments until the segments are small enough to make the lightning bolt pleasantly jagged. Smaller bolts are allowed to stretch out from some of these points, much like the way real lightning branches.
In a similar manner, a velocity is assigned to each point. The two endpoints are assigned velocities based on the movements of the entities connected by the bolt, and the in-between points have averaged and then slightly randomized velocities. This makes the bolt appears to warp in random ways before it vanishes. The movement is subtle, but it makes the bolts look much more natural and alive.
All these points are connected by thin polygons that face out of the screen. A simple texture is applied to the polygons, which makes the bolts look fairly realistic and much less polygonal. The textured polygons are drawn as pure white, and their brightness flickers a little.
To add color I draw a colored version of the same lightning bolt into a glow buffer. The glow buffer is then blurred and drawn on top of the existing image to make lightning and other specific parts of the scene look brighter. This creates a colored aura around the white lightning. Color is also implied by light sources that illuminate the scene near the lightning bolts. It would have been difficult to make decent lightning without already having good lighting and glow systems.
A good lightning sound effect took a while to find. The usual tzzzz tzzzz electric sounds are alright for short circuit effects, but they really don’t sound like lightning. I wanted loud pops like you would hear from a large electrostatic generator. The solution I found was to use a truncated bullwhip sound. If you skip the whoosh leading up to a bullwhip crack and play the sound starting in the middle of the crack, it sounds quite electric. I also add some rumbling thunder on occasion for good measure. You can hear all this in the accompanying video.