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
      interval
    1 filename
      interval
    ...

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;
      }
      else
      {    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 http://www.cocos2d-iphone.org/forum/topic/7414#post-43466.

From Cocos2D forum thread: http://www.cocos2d-iphone.org/forum/topic/9181?replies=5#post-59152

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s