Monday, December 21, 2009

Dynamically create and loop through MovieClip instances

Task: You need to dynamically create and then loop through MovieClips.
Solution: Use DisplayList and DisplayListContainer container methods.

var container:MovieClip = new MovieClip();
addChild(container);
var numItems:Number = 250;
var stageWidth:Number = stage.stageWidth;
var stageHeight:Number = stage.stageHeight;
function initClips():void
{
var c:MovieClip;
for(var i:Number = 0; i <>
{
c = new circle_mc();
randomizeClip(c);
container.addChild(c);
}
}
function randomizeClip(clip:MovieClip):void
{
clip.x = Math.random() * stageWidth;
clip.y = Math.random() * stageHeight;
clip.scaleX = Math.random() * 2;
clip.scaleY = Math.random() * 2;
var c:ColorTransform = new ColorTransform();
c.color = (Math.random() * 0xFFFFFF);
clip.transform.colorTransform = c;
clip.alpha = Math.random();
}
function onEnterFrame(event:Event):void
{
var c:MovieClip;
for(var i:Number = 0; i <>)
{
c = MovieClip(container.getChildAt(i));
randomizeClip(c);
}
}
initClips();
addEventListener(Event.ENTER_FRAME, onEnterFrame);


Play an embedded sound in AS3

Task: You need to play a sound contained within your content and set its volume.
Solution: Use the Sound, SoundChannel, and SoundTransform classes to play and
manipulate sounds.

function onSoundComplete(event:Event):void
{
trace("sound is completed");
}
var my_sound:Sound = new beep_id();
var sTransform:SoundTransform = new SoundTransform();
sTransform.volume = .5;
var channel:SoundChannel = my_sound.play();
channel.soundTransform = sTransform;
channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
Setting the class name for an embedded
sound for ActionScript 3

Dynamically load and display an image in AS3

Task: You need to dynamically load and display an image.

var request:URLRequest = new URLRequest("image.png");
var loader:Loader = new Loader();
loader.load(request);
loader.x = 100;
loader.y = 100;
loader.rotation = 20;
loader.alpha = .5;
addChild(loader);

Dynamically load and play a sound in AS3

Task: You need to dynamically load and play an MP3 file.

var url = new URLRequest("sound.mp3");
var sound = new Sound();
sound.load(url);
sound.play();

Load and read XML in AS3

Task: You need to load and read an XML file.

onXMLLoad(event:Event):void
{
var xml:XML = new XML(event.target.data);
trace(xml);
trace("Number of Contacts : " + xml..person.length());
trace("First contact’s favorite food : " + xml.contacts.person[0].favoriteFood);
}
var loader:URLLoader = new URLLoader();
var url:URLRequest = new URLRequest("contacts.xml");
loader.addEventListener(Event.COMPLETE, onXMLLoad);
loader.load(url);

Note: examples, use the following XML contained in a file called contacts.xml:

<xml>
<contacts>
<person>
<name>Mike Chambers</name>
<favoriteFood>Bacon</favoriteFood>
</person>
<person>
<name>John Doe</name>
<favoriteFood>Pez</favoriteFood>
</person>
</contacts>
</xml>