How to Snap, Crackle, and Pop in AS3

Published February 09, 2010
Advertisement
Here's a little quickie trick that took me a bit of googling to bring back. In old incarnations of ActionScript, sounds were pretty simple. If you wanted to grab a sound out of the Library (AKA embedded in your SWF), you did it like so. . .

var snd:Sound = new Sound() // make an empty Sound object
snd.attachSound("sp0") // load the sound "sp0" from the library
snd.start() // play the sound

Simple enough. Of course, there are all kinds of things you can do to the Sound object to pan it or play it from the middle, etc. But if you just wanted to quickly load and play a sound effect, this is the way to do it.

AS3's model of "streamline every danged thing" made this process slightly simpler. Every sound in your library is now a sound class in your global namespace, so you can now do this. . .

var snd:sp0 = new sp0() // instantiate an instance of "sp0"
snd.play() // and play it

Now then, that's pretty intuitive. But it does have a problem, and that's that my sounds are now objects rather than things I can reference with a variable. And if I wanted to do something like. . .oh. . .load up ten sounds into an array, it would get hairy. I can't just make an array that loads up snd.attachSound("sp"+i) into an array of Sound objects so I can address 'em by number. I'd have to put up a line of code for every object, and that's just sloppy.

AS3 does, however, have a function that can get you an object's class definition given a string representation of the name. So you can do the very similar. . .

var snd:Object = new (getDefinitionByName("sp0") as Class)
snd.play() // and play it

The getDefinitionByName() function looks up variable in the global namespace and returns it as a Class (after we've cast it with "as". So now I can once again load up a pile of sounds like so. . .

var numSounds = 4
var MySounds = new Array(numSounds)

for (var i=0; i{
var snd:Object = new (getDefinitionByName("sp"+i) as Class)
mySounds = snd // and stuff that sound into an array
}

And this is nice for games like Pop Pies 2 where I make a staccato "chain of firecrackers" sound by playing one of four random "pop" sounds in rapid succession for each pie that explodes. Now I can just call MySounds[int(Math.random()*numSounds)].play() at a set interval, and I get a nice snap crackle pop.
0 likes 2 comments

Comments

TANSTAAFL
I suppose you could also use eval (unless they dumped eval in AS3)?
February 10, 2010 07:59 AM
johnhattan
Yeah, eval is gone in AS3, as it allows you to execute any string you can construct and is pretty-much incompatible with a real compiler.

The upside is that AS3 compiles to a real VM assembly and is JIT compiled by the plugin, so executing code is way faster.
February 10, 2010 01:15 PM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement