Flash: Detecting the end of an animation July 24, 2008
Say you have an animated character in a game, that others need to know when they are through playing their animation. Here are a few approaches:
Let's first assume we have a generic object named 'player_mc' that is our animation. We also have a centralized controller script closer to the root, that has a function like:
-
function onAnimationComplete(evt:Event = null):void{
-
//do something
-
currentPlayer = evt.target as MovieClip;
-
currentPlayer.gotoAndStop("still");
-
}
Note that we use evt = null just in case we want to use call the function without passing it an event.
1) Using addFrameScript
-
var init:Boolean;
-
if(!init){
-
/// !init check, this block is only needed when pasting on timeline
-
// to keep it from activating more than once when the movieClip recycles
-
addFrameScript(totalFrames -1, onAnimationComplete);
-
init = true;
-
}
-
-
Just remember if doing that approach, addFrameScript uses a frame number one less that what you see in Flash.
This approach is safer when indexing frame labels prior (e.g. with UIUtil) to map say a frame label of "AnimationFinishedFrame" to the frame number for addFrameScript to use.
-
addFrameScript(com.troyworks.ui.UIUtil.getNumberOfFrameLabel("AnimationFinishedFrame", onAnimationComplete);
-
2) Using Event Bubbling
Just communicate up the display list.
-
player.addEventListener("ANIMATION_COMPLETE", onAnimationComplete);
Then
-
//inside the player on last frame of the player animation
-
-
stop();
-
dispatchEvent(new Event("ANIMATION_COMPLETE", true, true));
For more info see here.
3) Use Singleton/Static or Stage as a message bus.
like 2 but using the stage or some other easy to access to communicate without bubbling.
4) Poll for Progress
This is a bit more work, but get's you the ability to find out more about the progress, eg. showing a progress bar for percentage played.
-
player.addEventListener(Event.ENTER_FRAME, onENTER_FRAME
-
-
function onENTER_FRAME(evt:Event):void{
-
var playermc:MovieClip = evt.target as MovieClip;
-
-
if(playermc.currentFrame == playermc.totalFrames){
-
onAnimationComplete();
-
}
-
}
Hope that helps.

Add a Comment: