flash event listener for movieclip end?

Dancer picture Dancer · May 12, 2011 · Viewed 24.2k times · Source

Could anyone advise the best way to trigger a functiont when a movieclip animation finishes? I figure an eventlistener could handle this, but not sure the best way to go about it. Thanks Paul

Answer

Marty picture Marty · May 13, 2011

There are a few ways to go about this:

  1. Simply call the function from the last frame of your animation.
  2. Dispatch an event on the last frame of your function and listen for it elsewhere.
  3. The long but effective / neat / recommended way.

In reference to point 3, I would create a base class for your object. This way you can apply the same logic to multiple elements being animated.

Something like this:

package
{
    import flash.display.MovieClip;
    import flash.events.Event;

    public class AnimatingObject extends MovieClip
    {
        // constants
        public const ANIMATION_COMPLETE:String = "animation_complete";

        /**
         * Constructor
         */
        public function AnimatingObject()
        {
            addEventListener(Event.ENTER_FRAME, _handle);
        }

        /**
         * Called on dispatch of Event.ENTER_FRAME
         */
        private function _handle(e:Event):void
        {
            if(currentFrame == totalFrames)
            {
                var evt:Event = new Event(ANIMATION_COMPLETE);
                dispatchEvent(evt);
            }
        }
    }
}

Now we can listen for "animation_complete" and do stuff accordingly.

package
{
    import flash.events.Event;

    public class MyAnimatingObject extends AnimatingObject
    {
        /**
         * Constructor
         */
        public function MyAnimatingObject()
        {
            addEventListener(ANIMATION_COMPLETE, _lastFrame);
        }

        /**
         * Called on dispatch of AnimatingObject.ANIMATION_COMPLETE
         */
        private function _lastFrame(e:Event):void
        {
            trace("i'm done");
        }
    }
}