Sprite Sheet Animation in Cocos2D – An Example

By | March 14, 2011

Hi,

Suppose you have a sprite sheet of the desired animation you want. But how will you use that sprite sheet animation in your program using cocos2D? That’s simple. See the following code first.


//Initializing a CCSpriteBatchNode with our sprite sheet image
CCSpriteBatchNode *newSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"jumpingOver.png"];

//Adding the spriteSheet to the layer & setting the z orientations
[self addChild:spriteSheet z:14];

//Creating Frames from the frames file jumpingOver.plist
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"jumpingOver.plist"];

//Initializing a sprite with the first frame from plist
CCSprite *jumper = [CCSprite spriteWithSpriteFrameName:@"jump1.png"];

//Creating an NSMutableArray for adding the frames from plist
NSMutableArray *framesArray = [[NSMutableArray array] retain];

//Iterating for the total number of frames from plist
//Here supposing our jumpingOver plist have 15 images
for(int i=0; i<15; i++){
//Adding frames to our framesArray from the frames
[turningFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"jump%d.png",i]]];
}

//Creating an animation using the frames in framesArray
CCAnimation *jumping = [CCAnimation animationWithFrames:framesArray delay:0.25f];

//Setting our jumper sprite sprite sheet animation to the position of one another sprite
//oldSprite is our previous sprite on that position we are adding the animation
jumper.position=oldSprite.position;

//Creating action from the animation jumping
CCAction *jumpAction= [CCAnimate actionWithAnimation:jumping];

//running the action on jumper sprite with the sprite sheet animation action on jumpAction
[jumper runAction:jumpAction];

//Adding the jumper sprite to the layer with z orientation
[self addChild:jumper z:15];

🙂

One thought on “Sprite Sheet Animation in Cocos2D – An Example

  1. Antonia Hardison

    I’d be inclined to give carte blanche with you one this subject. Which is not something I usually do! I enjoy reading a post that will make people think. Also, thanks for allowing me to comment!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *