About a year ago I posted here about character animation with sprite sheets, including sample code that included the AnimSprite class. Lately all of my projects are using Starling.
As a new framework, I half expected Starling to drop legacy classes that are not useful anymore – but for some reason they carried over MovieClip with its antiquated interface. To be sure, I avoid MovieClip like a plague. In classic Flash it was (and still is) one of the worst offenders of memory and performance, and notorious for sapping CPU cycles even when it’s not playing. The Starling version, although better on performance, is still not very easy to use and requires too much wiring and boilerplate code for even simple use-cases.
In order to handle animated characters, I ported my AnimSprite class to starling and made a few improvements, to make it simpler and easier to use. The code is available on Gist.
The main features I needed and wrote into the class are:
- Ability to handle multiple sequences
- Playing loop and single sequence with variable frame-rate
- Simple notification when animation completes
- Optional automatic attach to starling Juggler
When defining sequences from the sprite sheet you provide the base name of the numbered frame and AnimSprite does the rest for you. I also added a reverse sequence so animation could be played backwards as well.
Simple example of setting up Animsprite:
1 2 3 4 5 6 7 8
// Initialize with a sheet (TextureAtlas) var hero:AnimSprite = new AnimSprite(sheet); // Define the sequence: first param is used as a key, // the second is the base texture name in the sprite sheet hero.addSequence("fly", "fly"); // looped //... Starling.juggler.add(hero); hero.play(); // same as hero.play("fly") since it's the only sequence
For playing a non loop sequence there is a convenience function attachAndPlayOnce. The second parameter is a boolean flag to determine if the object stays visible after the sequence is done playing.
1 2 3 4
// Non loop hero.addSequence("jump", "jump", false); //.. hero.attachAndPlayOnce("jump", true);
A different use case will have few sequences, and allows to play and stop any of them with optional callback at the end. To do that simply call play() with the sequence name.
Get the code for AnimSprite from Gist here.