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

Source

























Previous Entry Freebie on the cloud
Next Entry Data loss
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement