How to load and animate multiple spritesheets in Cocos2D?

The problem:

I can’t fit all my animation frames in one spritesheet, so I made two, can I use multiple spritesheets in one animation?

The solution:

And this is what I came up with:

My animation files information are loaded from a plist that looks like this:

animation array
    0 filename
    1 filename

The code:

NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:@"anim.plist"];
NSDictionary *data = [[NSDictionary alloc] initWithContentsOfFile:DataPath];

NSArray *animationSpritesheets = [data objectForKey: @"animation"];
id *animationSequence = nil;

for(int i=0; i<[animationSpritesheets count]; i++)
{     NSDictionary *animationSpritesheet = [animationSpritesheets objectAtIndex: i];
      NSString *fileName = [animationSpritesheet objectForKey:@"filename"];
      float interval = [[animationSpritesheet objectForKey: @"interval"] floatValue];
      [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:[NSString stringWithFormat:@"%@.plist", fileName]];
      CCSpriteSheet *spriteSheet = [CCSpriteSheet spriteSheetWithFile:[NSString stringWithFormat:@"%@.png", fileName]];
      [self addChild:spriteSheet];

      NSMutableArray *animFrames = [NSMutableArray array];
      NSString *animPath = [Path stringByAppendingPathComponent: [NSString stringWithFormat:@"%@.plist", fileName]];
      NSDictionary *animSpriteCoords = [[NSDictionary alloc] initWithContentsOfFile: animPath];
      NSDictionary *animFramesData = [animSpriteCoords objectForKey:@"frames"];

      for(int i = 1; i <= [animFramesData count]; ++i)
      {    [animFrames addObject:
           [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
           [NSString stringWithFormat:@"%@%d.png", fileName, i]]];

      CCAnimation *animation = [CCAnimation animationWithName:@"animation" delay: interval frames: animFrames];
      id action = [CCAnimate actionWithAnimation: animation restoreOriginalFrame:NO];

      if (!animationSequence)
      {    animationSequence = action;
      {    animationSequence = [CCSequence actions: animationSequence, action, nil];

[sprite runAction: animationSequence];

The code will play the multiple spritesheets in a sequence, the CCSequence code is based on

From Cocos2D forum thread:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s