You've successfully subscribed to Nicholas Workshop
Great! Next, complete checkout for full access to Nicholas Workshop
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Animated Sprites In Cocos2D

Nicholas Wong
Nicholas Wong

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"];  
Unsorted

Nicholas Wong

Fullstack software engineer with strong background in computer science and extensive experience in software engineering and architecture. Studied in NYU, worked in Yahoo, Rakuten and Manulife.