Dynamically adding movieclip to stage as3

actionscript-3movieclip

I have buttons on the stage (run1_btn – run5-btn) that when clicked adds a movie clip to the stage.(hand) The movie clip contains a few frames of animation. When a button is clicked the movieclip gets added but the animation is already finished.
I thought that when the mc got added to the stage then the animation would start, but this does not seem to be the case.
Does anyone know a way around this.

Here is my code:

var handSlap:hand;
handSlap = new hand();

//event listeners
newPig.run1_btn.addEventListener(MouseEvent.CLICK, clickArea);
newPig.run2_btn.addEventListener(MouseEvent.CLICK, clickArea);
newPig.run3_btn.addEventListener(MouseEvent.CLICK, clickArea);
newPig.run4_btn.addEventListener(MouseEvent.CLICK, clickArea);
newPig.run5_btn.addEventListener(MouseEvent.CLICK, clickArea);




//functions
function clickArea(evtObj:MouseEvent):void
{
    trace(evtObj.target.name);
    addChild(handSlap);
    handSlap.x =200;
    handSlap.y=200;

}

Best Answer

possibly more elegant (depends on your point of view), it ensures that in any context the hand will restart its timeline animation when it's added to the stage:

hand.addEventListener(Event.ADDED_TO_STAGE, onHandAddedToStage, false, 0, true);
function onHandAddedToStage(event:Event):void
{
    var mc:Movieclip = MovieClip(event.currentTarget);
    mc.gotoAndPlay(1);
}

If you're not familiar with the event model, the "false, 0, true" bit just ensures that if you ever need to unload the hand it won't get snagged by the event listener and stay in memory, probably you don't need it but it does no harm.

Related Topic