Animated Sprites In Cocos2D

Animated Sprites In Cocos2D

I have been working with Cocos2D for a while and I am still a newbie. The way to deal with animations in Cocos2D 1.0.0 – the stable version currently – is different from the way before using CCSpriteSheet. Now Cocos2D adapts animations as cache shared in the project using CCSpriteFrameCache. It also requires a plist file as well as a texture file.

First, put the following assets into the project “Resources” folder to let the program use.

  • grossini.plist – The file contain the animation information such as frame details.
  • grossini.pvr.gz – The texture file in pvr format which allow better performance in Cocos2D.

Second, add the following codes into the function init. Take a look at the comments for program explanation. =]

// Capture the window size  
CGSize size = [[CCDirector sharedDirector] winSize];

// Load the plist into the cache  
CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];  
[cache addSpriteFramesWithFile:@"grossini.plist"];

// Create sprite with the first frame  
CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"grossini_dance_01.png"];  
sprite.position = ccp( size.width/2, size.height/2);  
sprite.anchorPoint = ccp(0.5f, 0.5f);

// Create array for the animation frames  
NSMutableArray *animFrames = [NSMutableArray array];  
for(int i = 0; i < 14; i++) {  
  CCSpriteFrame *frame = [cache spriteFrameByName:[NSString stringWithFormat:@"grossini_dance_%02d.png",(i+1)]];  
  [animFrames addObject:frame];  
}

// Convert the array into animation  
CCAnimation *animation = [CCAnimation animationWithFrames:animFrames];

// Run the sprite with the created animation and display it by adding it to the scene  
[sprite runAction:[CCRepeatForever actionWithAction: [CCAnimate actionWithDuration:2.8f animation:animation restoreOriginalFrame:NO] ]];  
[self addChild:sprite z:0];  

After all, don’t forget to deallocate the resources loaded in cache in function dealloc.

// Deallocate the resource in cache  
CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];  
[cache removeSpriteFramesFromFile:@"animations/grossini.plist"];