Goal: Animate a MovieClip at an arbitrary speed during runtime.

Method: Store a custom frame Number. Increment it every frame, loop it around if the Number is out of bounds. Round the value and use it as a parameter for gotoAndStop().

The Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var cFrame:Number; //The current frame stored in a Number
var animationSpeed:Number; //How fast the MC should animate
//Stored in frames per 1 frame
 
//Initialization Function
cFrame = this.currentFrame;;
addEventListener(Event.ENTER_FRAME, animate, false, 0, true);
gotoAndStop( this.currentFrame );
 
//animate(e:Event)
cFrame += animationSpeed;
if (cFrame > (this.totalFrames))
	cFrame = cFrame - (this.totalFrames - 1);
gotoAndStop( Math.round( cFrame ) );
gotoAndStop(0);

Notes

  • The frame array AS3 uses for its’ MovieClips has values of 1 to totalFrames. Setting it to 0 results in it being upped to 1.

  • Setting the current frame to anything besides an integer value within the valid number of frames will cause the MovieClip to ignore the value.

Caution
Setting animationSpeed greater than totalFrames may break this function, depending on how big the value is.

—-
From my look through Google, there are very few if any articles that address this topic. It’s not particularly difficult to do, but I found no built in support for custom animation speed within ActionScript 3.

Related posts:

  1. Avoiding the Compiler’s Whip: 9 Flash AS3 Tips for Beginners
  2. Box2D SVG Parser with Curve Support
  3. Creating Levels in Box2D