# Use FlxAnim to Animate a FlxSprite in Flixel on FlashBuilder

I am trying to animate a FlxSprite, whose image I loaded from an embedded sprite sheet. I instantiate the sprite like this:

// embedding a png file given a relative path
[Embed(source="../Images/BatGraphic.png")] public var Bat_Enemy:Class;
override public function create():void
{
//instantiate bat sprite
bat = new FlxSprite(FlxG.width/2-5,FlxG.width/2);

var frames:Array = new Array(12);


I use this function to add the animation to the sprite, it essentially just calls the Flixel API:

public function AddAnimationToSprite(sprite:FlxSprite, frames:Array,animName:String,frameRate:int):void
{
var animation:FlxAnim = new FlxAnim(animName,frames,frameRate,true);

}


Then, in the update function, I call the FlxSprite play method to animate the sprite:

public function update:void()
{
/*animate relevant sprites*/
bat.play("batAnimation",true);
/*end animation*/

/*update screen based on player position*/
super.update();
}


Yet, the sprite does not animate. Is there a step I am missing? How do you use FlxAnim to animate a FlxSprite?

Update: I altered the code so that the FlxAnim.play() is called in the create as suggested as follows:

//instantiate bat sprite
bat = new FlxSprite(FlxG.width/2-5,FlxG.width/2);

var frames:Array = new Array(12);
var batAnim:FlxAnim = new FlxAnim("batAnim",frames,30,true);

bat.play("batAnim");


However, still nothing happens. Potentially, I don't have the right number of frames, since I only wanted to use the first row of sprites in the sheet to animate. But even if the number of frames were off, it should still be animating in some fashion right? Like flickering between two sprites? What am I missing here? Is 30 the appropriate fps for Flixel animations?

Simple, you're calling bat.play("batAnimation",true); in your update loop. That means, your animation will restart every frame, resulting in a still image.

The second parameter to the play function is a flag whether or not the animation should be forced to restart (see docs). So either call:

bat.play("batAnimation", false);


in your update loop, or what I would consider a better approach is to call bat.play("batAnimation",true); somewhere outside the update method. For example here:

...

• Incidentally I made exactly the same mistake recently with FlashPunk. API designers, please don't overload functions with extra boolean parameters - add a new function name, eg PlayFromStart! – Kylotan Dec 29 '12 at 10:38