Categories Displayed in Flash

Flash: Detecting the end of an animation

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:

  1. function onAnimationComplete(evt:Event = null):void{
  2. //do something
  3.  currentPlayer = evt.target as MovieClip;
  4.  currentPlayer.gotoAndStop("still");
  5. }

Note that we use evt = null just in case we want to use call the function without passing it an event.

1) Using addFrameScript

  1. var init:Boolean;
  2. if(!init){
  3.        /// !init check, this block is only needed when pasting on timeline
  4.       // to keep it from activating more than once when the movieClip recycles
  5.         addFrameScript(totalFrames -1, onAnimationComplete);
  6.         init = true;
  7. }
  8.  
  9.  

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.

  1. addFrameScript(com.troyworks.ui.UIUtil.getNumberOfFrameLabel("AnimationFinishedFrame", onAnimationComplete);
  2.  

2) Using Event Bubbling

Just communicate up the display list.

  1. player.addEventListener("ANIMATION_COMPLETE", onAnimationComplete);

Then

  1. //inside the player on last frame of the player animation
  2.  
  3. stop();
  4. 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.

  1. player.addEventListener(Event.ENTER_FRAME, onENTER_FRAME
  2.  
  3. function onENTER_FRAME(evt:Event):void{
  4.   var playermc:MovieClip = evt.target as MovieClip;
  5.  
  6.    if(playermc.currentFrame == playermc.totalFrames){
  7.        onAnimationComplete();
  8.    }
  9. }

Hope that helps.

Add a Comment: