开发者

Dynamically adding movieclip to stage as3

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(MouseE开发者_JAVA百科vent.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;

}


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.


  var newPig:pig;
newPig = new pig();
addChild(newPig);
newPig.y=360;
newPig.x=350;

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);

handSlap.addEventListener(Event.ADDED_TO_STAGE, onHandAddedToStage, false, 0, true);


//functions
function clickArea(evtObj:MouseEvent):void
{
    trace(evtObj.target.name);

    addChild(handSlap);
    handSlap.x =200;
    handSlap.y=200;


}

function onHandAddedToStage(event:Event):void
{
    var mc:MovieClip = MovieClip(event.currentTarget);
    mc.gotoAndPlay(1);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜