Playing an gif kind of animation in cocos2d for iPhone/iPad/iOS

Using this post, I will describe the answer of following question.

‘How to play simple gif animation in iphone/ipad using cocos-2d?’

Here is the animation that we are going to use in our sample project.

Car Animation sugartin cocos2d

This can help to the beginners for game-development. I won’t write too much.
I will directly describe to the point for it.
There are two options for this tutorial for you.

Option 1 : follow the steps I have written here.
Option 2 : go through the video included within this post.

Here are the contents describing the steps for achieving our goal.

01. Open your gif animation file.
02. extract & save each frame as a separate image.
03. Download Zwoptex . Thank you Zwopple & Zwoptex, for keeping it free. I really appreciate that.
04. Import all frames.
05. Apply settings & publish
06. Import plist & png file into your project.
07. add all frames into frame-cache.

// add all frames into cache
CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
[frameCache addSpriteFramesWithFile:@"CarAnimation.plist" textureFilename:@"CarAnimation.png"];

08. create a sprite using a sprite-frame from frame cache.

// add sprite-batch-node
CCSpriteBatchNode *sbn = [CCSpriteBatchNode batchNodeWithFile:@"CarAnimation.png"];
[self addChild:sbn];

09. Add sprite in the center of screen.

	// add the sprite to center of screen.
        CCSprite *s = [CCSprite spriteWithSpriteFrameName:@"01.png"];
        CGSize winSize = [[CCDirector sharedDirector] winSize];
        s.position=ccp(winSize.width/2,winSize.height/2); // center of the screen.
        [self addChild:s];

10. create an array of sprite-frames

         // now code for applying action.
        NSMutableArray *ar=[NSMutableArray array];
        for (int i=0; i<20; i++) {
            NSString *strFrameName =[NSString stringWithFormat:@"%02i.png",i+1];
            CCSpriteFrame *frame = [frameCache spriteFrameByName:strFrameName];
            [ar addObject:frame];

11. create an animation using array of frames

        // now create an animation using array of frames.
        CCAnimation *animation = [CCAnimation animationWithSpriteFrames:ar delay:0.2];

12. create an animate-action using animation.

         // now create an animate-action using animation.
        CCAnimate *animate = [CCAnimate actionWithAnimation:animation];

13. create an infinity-action using animate-action.

        // now create infinity action using animate-action
        CCRepeatForever *repeatF = [CCRepeatForever actionWithAction:animate];

14. apply the action to sprite.

        // now apply this action to sprite.
        [s runAction:repeatF];

Illustration using Video.



Leave a Reply

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