Home > ActionScript 3.0 > Sprite Player

Sprite Player

This is a tiny little lib to play multi-framed sprites of different type in a common way. The frame analogy should be familiar.

The concept is that frames are advanced according to a differential. If you set this differential to 1, then it will play a MovieClip, for instance, exactly as it would play by itself. If instead you set it to 0.5 it will run at half-speed. Set it to -2 and it will play in reverse at double speed.

In the demo below, there’s a MovieClip and a tile-sheet-blitted-to-BitmapData of the same animation being controlled by a SpritePlayer. Adjust the slider to see how the differential effects playback.

Demo: Drag the slider to change the frame rate differential.

Get Adobe Flash player

It’s a pretty sloppy implementation (see: MovieClipWrapper), but it should get the point across. A SpritePlayer has a reference via composition to an implementation of IPlayable, which is implemented as a simple wrapper for the MovieClip and as example in a TileSheetSprite class for the blitting technique. The main method is in solving for the next frame, which is done without any multiplication or modulo operation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public function next() : int
{
 
	var deltaFrame:int = differential >> 0;
	remainder += differential - deltaFrame;
 
	if( Math.abs( remainder ) >= 1.0 )
	{
 
		var rdt:int = remainder >> 0;
 
		deltaFrame += rdt;
		remainder -= rdt;		
 
	}
 
	var nextFrame:int = target.currentFrame + deltaFrame;
 
	if( nextFrame > target.totalFrames ) nextFrame -= target.totalFrames;
	else if( nextFrame < 1 ) nextFrame += target.totalFrames;
 
	target.gotoAndStop( nextFrame );
 
	return target.currentFrame;
 
}

A remainder property is stored to collect the difference between the change in frames, which is an integer, and the differential, which is a float. In one iteration of this algorithm, it is clear that remainder can not be greater than or equal to 1 (or less than or equal to -1). So when it does accumulate to 1 or greater, the delta frame is incremented by the rounded remainder (1 or -1), and this value is subtracted from the remainder. Then the algorithm just wraps nextFrame in the case that it exceeds the range of frames.

So it naturally supports playback in both directions at any differential, though there’s a cap put on the differential so that it’s less than the total number of frames for the sprite being played.

source (MIT License)

Categories: ActionScript 3.0 Tags:
  1. No comments yet.
  1. January 28th, 2011 at 12:50 | #1