Flash Lightning

[kml_flashembed movie=”/flash/Lightning/miniLightning.swf” width=”300″ height=”400″ bgcolor=”#000000″ wmode=”normal” /]

Lighting is a class that dynamically draws a lightning strike. The input fields act like the Photoshop palettes. Meaning once you select an input field you can use the up/down arrows to increment/decrement the value. Holding the shift-key down will increase/decrease faster. Values less than 10 change by .1 / 1 whereas values greater than 10 increment by 1 / 10. See it yourself right here. Here’s a short animation of how the lighting is created.

You can download a zip file with all the source files you’ll need to look over the code. I would appreciate an email if you would like to use this on your site. The Lightning class file is extensively commented. Enjoy.

Here’s a basic walkthrough of how the Lightning class works:

You probably want to use a onMouseDown to initiat the class so use the code below in your FLA.

onMouseDown = function():Void {
var bolt:MovieClip = _root.createEmptyMovieClip(“bolt”, 0);
// custom settings go below here

var strike:Lightning = new Lightning(bolt);
}

Inside the onMouseDown function you want to create an empty MovieClip that the Lightning can be drawn on. It also insures that the properties get erased from instance to instance since the bolt MovieClip is always created at the same depth the previous incarnation will be wipped out, with it’s properties, every time you click.

A MovieClip is all you need to pass to the class constructor. However there are 34 essential properties that determine things like the colors, effects, where the strike starts and ends, ect. The good news is that if you don’t pass these properties then the class will set them to defaults.

If you would like to change a setting then add code like this after creating the emptyMovieClip:

bolt.durationTime = 1000;

That’s all it takes to create lightning as you like it.

How the Lighting class works.

Now lets walk through how the Lightning class goes about its business.

Lightning()

The class construtor is the first function to run when creating a new instance of the Lightning class. First it calls the setDefaults() method which runs through all the settings. Any settings that are undefined – haven’t been set – are given defaults. Now the makeLightning() method is called which, guess what, makes lightning.

makeLightning()

The makeLighting() method gets called from the class constructor and also every time a branch is created. With that in mind the first thing it does is check to see if we are on the main branch because it gets treated slightly differently. There are two main things that get done for the main branch that don’t need to be done for the branches. That’s to create the blur and glow filters for our effects. It also takes care of how the lightning will fade out.

The last thing the makeLightning method does is call the getTerm() method.

getTerm()

You may be thinking at this point, “When are we actually going to draw something on the stage.” First we have to do some math to figure out where to do the drawing.

The xDist/yDist are simply getting the distances from where we are – cloudX/cloudY – to the point we need to get to – groundX/groundY.

The midTermX/Y variables are a point that is a fraction of that remaining distance.

The following if statement is extremely important. This is where we determin if we are close enough to the groundX/Y to just go directly there. Without this statement we would be in an infinite loop.

Supposing that we haven’t reached the ground we have have two more steps here. We have found a point that is between the cloudX/Y point and the groundX/Y but lightning that travels in a straight line would be boring. We need to introduce some randomness and this is where it happens.

var rndAngle:Number = Math.random() * 2 * Math.PI;
var rndDelta:Number = Math.random() * clip.termDelta;

clip.termX = clip.midTermX + ( rndDelta * Math.cos(rndAngle) );
clip.termY = clip.midTermY + ( rndDelta * Math.sin(rndAngle) );

All that does is move us in a random direction and a random distance from that point we found between the cloud and ground.

Now we do a little randomness to determine if we want to create a branch here. If so then we call the makeBranch() method. All that the makeBranch() does is create a new MovieClip in the current one, apply some settings, and then call the makeLightning() method again.

Finally, it’s time to call the drawStrike() method and use the drawing API to put some pixels on the screen. After that method runs we come back here and notice the last thing in the method is a call to getTerm(). But we’re in getTerm() already. We have gone though all the steps to make some lightning. Now it’s time to do it again, and again, and again with some recursion. Remember, one of the things that the getTerm() method does is check to see if we are close enough to our end point to end. So it’s safe to recurse because eventually it will break itself. (Okay, in practice I ran into numerous infinte loops and locked up my PC more times that I care to remember.)

drawStrike()

This is where we pull out the drawing API and make some pixels. After drawing the current lightning segment we reset where the cloudX/Y to where we just finished drawing to.

19 thoughts on “Flash Lightning

  1. Absolutely awesome job. I’m basically a virgin when it comes to creating code and flash like your lightning flash but I’m learning, well I’m trying to learn anyways. I have a question which I imagine you have been flooded with & are sick & tired of people asking & if true I sincerely apologize for asking, yet I must. Can your code some how be added to a myspace page so that everytime someone clicks to open a link a lightning bolt flashes from random spots above the pointer and ends just like it does in your flash demo a at the pointer. Ok in reality like real lighting starts at the pointer and shots up. Anyways is there a way to do this? If so or if you already have code for that is it possible to request that code from you. I of coarse would have no problems adding any links to any sites that your might request and or give full viewable credit to you.
    Any help, thoughts and or comments would be very appreciated.

    Signed,
    Code Virgin: DJJeremyD

  2. @Jeremy, The short answer is no. The reason is that you would have to create a

    to hold the lightning on top of the page content. That’s easy enough and would make it so that the lightning would work as you described. However, the underlying HTML, your page content, would not receive any Mouse events so you wouldn’t be able to navigate. I know, that’s a pretty big bummer because I wanted to do the same thing.

    It would work if you had a page that was all Flash. Then you could have the lightning in a MovieClip on top of everything else but the underlying content would still recieve Mouse events.

    Thank you for the compliments.

  3. Well….you could make it work, by having your flash code call the HREFS (the click links) of the underlying code, by telling it in advance the coordinates of the links (that are underneath) and having the flash float on top by setting the Z-order and with absolute positioning – you would of course have to set WMODE=transparent (note: the Nintendo WII doesnt seem to support transparent and WILL NOT support anything higher than Flash 7)

  4. I’m not following this, but it seems to me you could make it work by doing your mouse click and coordinate capture in the javascript, and then passing that to the flex via External Interface.

  5. Well, I'm a total new-born here… but how can you make all this awesome flash files transparent? I mean, where to add stuffs like " wmode=…" in xxx.fla??? Thanks in advance!!! :)

    1. @PaulVendar, I’m not sure what you’re asking. You want to use this somewhere – which you’re welcome to – and you need to know how to make the SWF transparent? If so then you pretty much have it there: wmode=transparent. That’s about it.

  6. OMG!!!!! That's excatly what I need rite now! That'll come in handy!!!!!! But i was wondering how to keep the lightening branch not just come from above… i mean, how to make'em start from a point and whenever and wherever yr mouse clicks, there comes a lightening branch right from that point… well, like this video game inFAMOUS website effect: http://www.infamousthegame.com… P.S. when you land on that site to chose language, there'll be a lightening branch follows yr mouse…

    1. @JessicaEvans, You can make the lightning start and end anywhere you want to. And if you want you can add a mouse listener so that when the mouse moves the lightning follows it. Take a look at the documentation and let me know if you have any problems.

  7. Hey, great work here!
    I am a noob when it comes to scripting but somehow have always succeeded to get it to perform the task..

    In your work, the function is triggered by a mouseclick.. However I wanted it to be triggered after a set amount of time, automatically, using setInterval.

    When I try doing that, flash outputs
    “256 levels of recursion were exceeded in one action list.
    This is probably an infinite loop.
    Further execution of actions has been disabled in this movie.”

    Is there a way to go around this and get the lightning to strike on timed intervals?
    Thank you in advance!

    God Bless.

    1. @a5aLien I’m sure there’s a way to do it. In fact I’m pretty sure I did that a long time ago. But I wrote this in AS2 so long ago I hardly remember how any of it works. I suppose you’re going to need to pass in simulated mouse coordinates. In fact you might have to create a new MouseClickEvent and give it the necessary values you want and pass that in. I think the error is coming from the settings you used. Try cutting back on the branching parameter or something like that and see if it goes away. I have a feeling that you’re using values that create too many branches.

  8. This is such a great project! Any chance I can use it in one of my projects? I’ll absolutely keep your info in the class file.
    Thanks,
    Dave

    1. @Dave Absolutely. Do whatever you want with the code. Unfortunately it’s all AS2. I’ve been kicking around the idea of redoing this using Away3D. That would be a fun project.

Leave a Reply

Your email address will not be published. Required fields are marked *