In this tutorial I am going to show you how to create relatively simple arcade-style explosions using ActionScript. To get started I would like you to take a look at the complete code, to get an idea of what you’ll be doing. Don’t worry if any part confuses you, I’ll explain each part step-by-step.
(Click with the mouse anywhere inside the movie to see an explosion.)
Here’s the code in it’s entirety:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | /* GLOBAL VARIABLES */ _global.gLEFT = 0; _global.gTOP = 0; _global.gRIGHT = Stage.width; _global.gBOTTOM = Stage.height; /* VARIABLES ON _root */ var maxSpeed:Number = 25; var minSize:Number = 4; var maxSize:Number = 10; var minFragments:Number = 50; var maxFragments:Number = 150; /* FUNCTION: Returns a random number between min and max (inclusive) */ function randRange(min:Number, max:Number):Number { var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min; return randomNum; } /* MAIN PROGRAM LOGIC */ onMouseDown = function():Void { var totalFragments:Number = randRange(minFragments, maxFragments); var fragment_mc:MovieClip; var depth:Number = this.getNextHighestDepth(); for (var i:Number = 0; i < totalFragments; i++, depth++) { fragment_mc = attachMovie("Fragment", "fragment" + depth, depth); fragment_mc._x = _xmouse; fragment_mc._y = _ymouse; fragment_mc._width = fragment_mc._height = randRange(minSize, maxSize); while (!fragment_mc.speedX) { fragment_mc.speedX = randRange(-maxSpeed, maxSpeed); } while (!fragment_mc.speedY) { fragment_mc.speedY = randRange(-maxSpeed, maxSpeed); } fragment_mc._alpha = randRange(10, 100); fragment_mc.cacheAsBitmap = true; fragment_mc.onEnterFrame = function():Void { this._x += this.speedX; this._y += this.speedY; if (this._x < gLEFT || this._x > gRIGHT || this._y < gTOP || this._y > gBOTTOM) { this.removeMovieClip(); } }; } }; |
Before we get started with the code, let’s make sure our document properties are the same. You can access the Document Properties dialog either by going Modify > Document..., or by pressing CTRL+J. Leave the document’s dimensions at the default of 550×400. Set the background color to black and the frame rate to 30.
There’s one more thing to do before we hit the code. We need to create a movie clip symbol that will be used as the basis for the fragments that make up the explosions. To make things easy, you can just make a white circle (CTRL+F8) - size not important - with coordinates (0,0), as I have done and name it “Fragment”. Make sure you give it a linkage name of “Fragment”. I encourage you to experiment with different colors and shapes for the fragment movie clip.
1 2 3 4 5 | /* GLOBAL VARIABLES */ _global.gLEFT = 0; _global.gTOP = 0; _global.gRIGHT = Stage.width; _global.gBOTTOM = Stage.height; |
To begin with we set four global variables which together define the boundaries of the game world. Since they are global, they are accessible from within any script. To keep things organised, I have placed all the code in one script attatced to the main timeline (Layer 1, frame 1). I’ve given gLEFT and gTOP a value of 0, gRIGHT has been set equal to the width of the Stage, as retrieved from Stage.width, and gBOTTOM has been set equal to the height of the Stage, as retrieved from Stage.height. This makes the game world equal to the visible screen size. Of course your free to set each boundary wherever you like.
1 2 3 4 5 6 | /* VARIABLES ON _root */ var maxSpeed:Number = 25; var minSize:Number = 4; var maxSize:Number = 10; var minFragments:Number = 50; var maxFragments:Number = 150; |
Following the global variables are five timeline variables (on _root). The first, maxSpeed, sets the maximum allowable speed for the fragments. The second, minSize, sets the minimum allowable size for the fragments. The third, maxSize, sets the maximum allowable size. The fourth, minFragments, sets the minimum allowable fragments per explosion, and the fifth, maxFragments, sets the maximum allowable fragments. You’ll see them put to use shortly.
1 2 3 4 5 | /* FUNCTION: Returns a random number between min and max (inclusive) */ function randRange(min:Number, max:Number):Number { var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min; return randomNum; } |
Next comes the definition of randRange( ). This function returns a random integer between it’s first and second parameters (inclusive). Let me explain how it works: It uses the random( ) method of the Math class which returns a random number which is equal to 0 or any number greater than 0 but less than 1 (often expressed as 0 <= n < 1), e.g. 0.24. This is all good and well, but it's no good if we want a random integer within a certain range. This is where randRange( ) comes in. First, it finds the difference between the larger parameter and the smaller parameter (expressed as max - min). But why is 1 added to the difference? Let’s imagine that min was 0 and max was 5, then their difference would be 5. If this was then multiplied by Math.random( ), the smallest possible result would be 0 when Math.random( ) returns 0, and the largest possible result would be just less then 5, since Math.random( ) will always return a number less than 1. When Math.floor( ) removes the fractional part of the number so far, we’re left with an integer between 0 and 4 (inclusive), not quite what we wanted. However, if we add 1 to (max - min) and multiply it by Math.random( ), we end up with a number anywhere from 0 to just less than 6. Now when Math.floor( ) works its magic, we get exactly what we wanted—an integer between 0 and 5 (inclusive). The only thing left for randRange( ) to do is add min to the random integer. This gives us a random integer within the specified range, whew! Try out randRange( ) with various values if you don’t believe me.
If all this has your head spinning, then relax because it’ll get easier from here on out.
Finally, the good stuff!
The code that actually creates an explosion is placed inside the onMouseDown handler on the root timeline. This code will execute when the mouse button is pressed, causing an explosion originating from the mouse’s current position.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /* MAIN PROGRAM LOGIC */ onMouseDown = function():Void { var totalFragments:Number = randRange(minFragments, maxFragments); var fragment_mc:MovieClip; var depth:Number = this.getNextHighestDepth(); for (var i:Number = 0; i < totalFragments; i++, depth++) { fragment_mc = attachMovie("Fragment", "fragment" + depth, depth); fragment_mc._x = _xmouse; fragment_mc._y = _ymouse; fragment_mc._width = fragment_mc._height = randRange(minSize, maxSize); while (!fragment_mc.speedX) { fragment_mc.speedX = randRange(-maxSpeed, maxSpeed); } while (!fragment_mc.speedY) { fragment_mc.speedY = randRange(-maxSpeed, maxSpeed); } fragment_mc._alpha = randRange(10, 100); fragment_mc.cacheAsBitmap = true; fragment_mc.onEnterFrame = function():Void { this._x += this.speedX; this._y += this.speedY; if (this._x < gLEFT || this._x > gRIGHT || this._y < gTOP || this._y > gBOTTOM) { this.removeMovieClip(); } }; } }; |
When onMouseDown executes, totalFragments is set to a random integer from minFragments to maxFragments. If this were 80, then 80 fragments would be created in this particular explosion. fragment_mc holds a temporary reference to each fragment, so that we can set up each fragment’s properties and methods. depth is then set to the next available depth. It is incremented by 1 after each iteration of the for loop to ensure that each fragment is given a unique instance name.
The for loop is used to create the fragments successively. First, attachMovie( ) is used to create a unique instance of the fragment movie clip symbol from the library (the one we created earlier). Next the newly created fragment is positioned at the mouse’s current location. The fragment’s width and height are then set to a random integer from minSize to maxSize. Following are two while loops. The property “speedX” has not yet been set and so has a value of undefined, which evaluates to false. But when combined with the logical NOT operator (!) the condition now evaluates to true, causing the body of the while to run. It is here that speedX is set to a random integer from -maxSpeed to maxSpeed (if maxSpeed were 50, then that would be from -50 to 50). So long as speedX is not 0, the while loop will finish running. Otherwise the while loop would continue running until speedX did not equal 0. The same logic applies to speedY. The fragment’s opacity is set to a random integer from 10 to 100, by setting it’s _alpha property accordingly.
Since the fragments do not change visually once they’ve been created (only their x and y position is changed), I’ve set each fragment’s cacheAsBitmap property to true which causes Flash to cache an internal bitmap representation of the movie clip. This increases the performance of the animation slightly, although it does use more ram.
Finally the fragment’s onEnterFrame handler is set. On each frame, the fragment’s x and y position is updated, by adding speedX and speedY respectively. Also, the fragment’s x and y position is checked to see if it breaches any one of the four boundaries of the game world, if it does, then the fragment removes itself from the Stage by invoking it’s removeMovieClip( ) method. That’s all there is to it.

Awesome loved it , keep going…….
Hai i like verymuch this program,how ya?
This is great. Would you consider doing a tutorial on making an image explode. I’m thinking like an intro. I want the image to explode then settle to the main site. But I have no clue how to do this. It’s driving me nuts. LOL!! Great tut!
Sarah
I’m glad you like the tutorial. As for the tutorial request, I’ll have a go at it and see what I can come up with
Update:
It’s actually quite simple to explode an image in Flash. You can use the Explode Timeline Effect.
With your image on the Stage, right-click it and select Timeline Effects > Effects > Explode. A dialogue will appear that will allow you to adjust the explosion effect to your liking.
Hope this helps.
Great tutorial! If I wanted to use this to create a fireworks effect without having to click, how would I do that?
Thanks,
Jon
Take a look at the tutorial on creating heat-seeking missiles. In it you’ll find a more practical implementation of the explosion code from this tutorial. Specifically, look at
explosion( ). All you need to do when you want an explosion is call this function with the x and y location where you want the explosion to originate from.Let me know if you need any more help.
thx 4 tutorial
this is good
great work….exellent tut..thanks for that….i want the same to happen without having to click….i’m trying with duplicate movie clip and arrays..but not getting the effect….can u help??
krutika.deshpande@gmail.com
When I copy/paste the code into flash and try to run it, it says the code is to complicated and might crash my computer (not the exact words, but you know what I mean I guess haha)
@krutika
It’s simply a matter of wrapping the explosion logic in a function, and then calling that function whenever you want an explosion. I’ve done this in the heat-seeking missiles tutorial.
@Tim
Most computers shouldn’t have a problem with running this script…of course, you will need to compile it as AS 2.0. What version of Flash are you using?
i assume im getting the same error as tim
i made the movie clip called it ‘fracture’, gave it the instance name ‘fracture’ [ later tested with ‘Fracture’ to see if it was a case problem ] and them simply pasted your code into the same frame [ but not on the object ]
the error i was given after a short wait was that a script is causing flash to run slowly and asked i wasnted to stop the script.
im using flash proffesional 8, and ive checked the publishing settings, theyre all set up for flash player 8 and actionscript 2.0.
any ideas? =S
thanks
@zoomj
What I’ve done here is create a new movie clip symbol, and given it a linkage name of ‘Fragment’. The code loads the symbol from the library.
This is done by
attachMovie( ). So you shouldn’t manually place any instances on the Stage.The first argument you pass to
attachMovie( )should be the linkage name that you gave the fragment movie clip. In the code you will see that this is ‘Fragment’. The likely cause of your problem is that you haven’t got this linkage name right.Hope this solves your problem
hi…i gave the linkage name but still it asks to abort the script…..i’ve not kept the clip manually on the stage…wat’s the problem ?
that was it =]
thanks for that, i just misunderstood, never even knew a linkage name exhisted.
I am copying the code directly from the site, but when i run the program and click it creates a whole bunch of instances that don’t move. and stay on the screen forever. Plz help, is it something with my enter frame settings.
@krutika
Have you copy/pasted the code exactly as it is here, or have you altered it in any way?
@Will
Firstly, you should check that the frame rate of your movie is appropriate, such as 30 fps, and the code should be attached to frame 1 of the main timeline.
So long as you’ve set up the document as stated in the tutorial, and have not altered the code, you shouldn’t have any problems.
figured it out i was making Fragment a button instead of a movie clip that fixed the problem. My question is why didn’t it work as a button?
@Will
Buttons do not possess an onEnterFrame event handler. As such, they can not be animated like a movie clip can. Buttons are great for making buttons though
sry if this is very far beyond the scope of this blog but i was thinking of another application of this program. What if on your first click you created the little elements that scattered over the stage, then had to click on them in order to clear the screen. How would this be done?? any suggestions are very apreciated
hiiii…..nice nice i played tht game for 1 hr nice game nice blasts
@Will
That’s an interesting idea.
I presume you’d want the fragments to decelerate until stopping somewhere on the Stage. To do this, you’d need to add a couple more properties to each fragment movie clip. Something like this:
And edit their onEnterFrame handler like so:
Place those statements at the top. To stop the fragments when their velocity becomes arbitrarily close to 0, you could do this:
If you only want the first click to result in an explosion, place the following statement at the end of the onMouseDown handler:
Now to clear them off the screen: You only have to add the following to the onMouseDown handler:
What about removing the hand that appears when you move the mouse over each fragment:
Hope this helps.
P.S. This blog never goes out of scope
can anyone tell me how to start?!?!? how do i get Actionscript!(i know it’s kind of sad asking, but i’m a newbie and ready to learn!)
You’ll need Flash, preferably Flash CS3. I’d recommend learning AS 3.0, although AS 2.0 is easier to learn.
An alternative is the free Adobe Flex 2 SDK. Here’s a great resource for learning AS: http://www.actionscript.org
Good luck!
Hi.
New to Flash and stumbled upon your cool tutorial.
Unfortunately when I paste the code try to to test the movie I get the following error:
Scene=Scene 1, Layer=Layer 1, Frame=1: Line 15: ‘{’ expected
function randRange(min:Number, max:Number):Number {
Scene=Scene 1, Layer=Layer 1, Frame=1: Line 18: Unexpected ‘}’ encountered
}
I’m using Flash MX version 6.0.
thanks.
Jack.
This is written in ActionScript 2.0. Flash MX 6 only supports ActionScript 1.0. This isn’t a problem however; you need only remove the strict data typing. Remove all ‘:Number’ and ‘:Void’ from the variable and function definitions.
Have fun
Hi.
Wow. Thanks for the quick response. I removed the data typing and the compile errors went away. However, now I just get a blank screen with no response when I click the mouse. I’ve created the “Fragment” movie and given it linkage as “Export for actionscript” and “Export to first frame”. I’ve also copied and edited the code into frame one.
Other than upgrading…would you have any other ideas?
thanks.
Jack.
@Jack
Have you given the fragment symbol the linkage name ‘Fragment’?
Make sure you have your document set up correctly; background color, frame rate etc., and that the fragment symbol is a distinguishable color.
I’ve compiled this script under AS 1.0, it works just fine. It wouldn’t hurt to upgrade though.
i typed the same script with alteration in var names…but it is not workingg…if i paste yrs things….it plays…linkage name, frame rate r as told….wat’s the problem ?
Hi - Missed removing a ‘:Number’ on one of the variables. Works great now. Very cool. thanks again!
Jack.
@krutika
If the script worked before you altered it, chances are you missed something. Double check that you’ve changed the variable names correctly.
@Jack
Glad I could help
hi….
i want to display images one by one by scripting only….trying out setInterval but not working properly…..help ….help…help….
@krutika
If you want to create the fragments programmatically, you should use the drawing API. Also, you might want to try onEnterFrame over setInterval for animation. Personally, I prefer to use an onEnterFrame handler.
i want to display images one by one by scripting only….trying out setInterval but not working properly….as u told i tried foloowing things but the screen is blank
_global.disp;
img = new Array();
var count:Number = 0;
var maxCount:Number = 10;
var depth = this.getNextHighestDepth();
for (var i:Number = 0; i=maxCount) {
clearInterval(intervalId);
}
count ;
}
pls help
i tried to remove the :void and :number like jack. and it doesnt work. it hangs up and display the white ball. im using macromedia 7 and AS 2.0. and pls, can you explain to me where can i see the linkage name. i cause i thought its instance name…
@Paul
Since your using AS 2.0, you don’t have to remove the strict data typing. As for the linkage: right click on the fragment symbol in the library (
Window > Library) and select Linkage…, make sure Export for ActionScript is checked. For Identifier, enter ‘Fragment’. Hopefully you shouldn’t encounter any more problems.Let me know how you get on.
thnx thats the right answer for my problem. its realy great but there’s one more thing. how can i hide the ball i made placed at coordinates 0,0??
@Paul
It sounds like you’ve put an instance on the Stage. The script creates instances of the fragment symbol dynamically, so there’s no need to manually place any instances on the stage. Just delete it from the Stage, and your good to go.
tnx. ur realy a great help.
@krutika
I’m guessing your showing me a segment of code. Not quite sure what your trying to do. Also, your missing a semicolon in your for loop. The for loop requires initializer, loop-test, and counting expressions, separated by two semicolons, even if any of those three expressions are empty. Perhaps your could clarify.
Hi. Great tutorial. Thanx a lot!
What if you wanted 2 dots of different colors to explode. Ive tried to edit the _mc instance and place another dot next to it - bad idea. I also tried to attach the script to a new layer in the timeline to play another movie (Fragment2_mc), changing everything in it’s script to Fragment2_mc but it only shows the original “Fragment_mc”
@JT
This is quite simple to do. Open up the fragment movieclip, create a new keyframe for each color you want. On each new frame, change the color of the fragment to the color you want.
Now you need only add one line of code to the
onMouseDownhandler:Hope this helps.
Perfect! Kudos
Can’t believe it’s that simple. I started out wrong with putting the new color fragment on the same keyframe. Wouldn’t have thought to put the extra line of code in the onMouseDown handler, but it seems to work fine without this line of code. Why is this extra line necessary?
@JT
By adding this extra line of code, we’re instructing the fragment movieclip to stay put on a random frame. If we don’t do this, the movieclip will loop, and each fragment will appear to flicker. You may not have noticed since the fragments move quite fast. The extra line of code ensures that each fragment remains a single color.
However, if you get the effect you looking for without it, then there’s no harm in omitting it.
I see what you mean. I only noticed it when looking at the slower moving fragments. But yeah, I prefer them not to flicker. I’m trying now to make the fragments scatter and then let all the fragments on the stage “magnetically” move back to the origin where they came from. Sort of like a reverse effect on the explosion but with more motion/elasticity/. I know how to call the elastic effect by applying the “Elastic.easeOut” on other things but haven’t had success with it on this particular explosion effect. I’m very new to AS, so at this point they just keep spawning from the origin and the performance gets slower and slower. Doesn’t need to have the elastic effect but just the reverse effect if possible.
O, what I meant to ask was, can you be of any assistance if you have time?
@JT
You could just use a basic spring force on the fragments. The fragments would be sprung to their origin, which you could store in some properties. This would give you an explosion/implosion effect.
If you don’t mind me asking, what do you want to use this effect for?
I’ve been into animation as a hobby for quite a while and I am trying to learn ActionScript so that I can use less keyframes and reduce the size of my files. I’m very new to ActionScript and I am trying to learn how certain things work in order to help me develop my characters in the way they move. (Sort of trying to figure out how realistic flash can actually be in terms of gravity, orbiting, flexibility, weight etc. …as if was a world of it’s own) I’m only learning from this and won’t actually be using this effect on anything. I made a black hole scene last year but I actually drew up a motion path for every little “planet” (on it’s own layer) that got sucked into it. The file size for only that together with the sound was over 10MB. I realized that I have to learn Actionscript in order to make everything more compact because my artwork can get very complex. I came upon a very interesting website http://www.riot.co.za - That was what sparked my interest in this type of movement. I then came upon your tutorial and saw that similar type of effect. That’s why I asked how to do the 2 colors and the return thing, to learn how to do that by avoiding keyframes as much as possible. This tutorial truly made me realize the power of ActionScript and I’m getting quite addicted. I’m not into web animation at all, I use AfterFX to combine my swf’s with video and stuff, so it’s a bit tricky for me to make things happen with Actionscript without the “user” clicking something to make something happen. ..but practice makes perfect I guess
@JT
ActionScript is a great tool for creating the realistic animations which you speak of. With some simple ActionScript, it’s possible to create very beautiful effects. I checked out http://www.riot.co.za - the effect used there is very nice. It’s good to hear your getting into ActionScript; it can be a lot of fun
it looks very cool, and works fast viewing from the browser, but when i put the code into flash it doesnt work and also crashes the pc, telling a script in this movie is causing flash player to run slowly… i dont have any idea what this could be.. i set it to actionscript 2.0 and i’m using flash 9 (CS3)… i have created the Fragment movie clip and set to 0×0 coordinates… i’ve done everything… it just doesnt work here… any tips??
i found out what was the error… i forgot to activate the LINKAGE thing! sorry guys.. it’s working perfectly now!
Cool effect, but doesn’t work in CS3 (with AS 2). The flash film is simply stopped and a message appears that the function takes too much cpu.
It is the same problem as “kist” describes, but it’s not the linkage here…
Any idea? Thx.