7.4. Reversing Playback

Problem

You want to play a movie clip’s timeline in reverse.

Solution

Use an onEnterFrame( ) event handler with the prevFrame( ) method.

Discussion

You can programmatically reverse the playback of a movie clip’s timeline with ActionScript. The onEnterFrame( ) event handler of a movie clip is called repeatedly at the same frequency as the movie’s frame rate. Therefore, if you create an onEnterFrame( ) method definition for a movie clip that includes a call to the prevFrame( ) method, the movie clip’s timeline will continually move to the previous frame at the movie’s frame rate:

myMovieClip.onEnterFrame = function (  ) {
    this.prevFrame(  );
};

If the movie clip’s playhead is already on the first frame, prevFrame( ) has no effect. Therefore, to loop the movie clip’s timeline while playing in reverse, add a conditional statement that goes to the last frame of the movie clip if it is already on the first frame. The current frame number is determined using the _currentframe property, and the last frame is determined using the _totalframes property:

myMovieClip.onEnterFrame = function (  ) {
  if (this._currentframe > 1) {
    // Play the clip backwards.
    this.prevFrame(  );
  } else {
    // Loop back to the end if we're already at the beginning.
    this.gotoAndStop(this._totalframes);
  }
};

See Also

Recipe 7.8

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.