Search code examples
cocos2d-iphone

Animate CCSprite


I am newer to cocos2d and preparing my demo game. I am moving a sprite from right to left using just a single image like a bird image moving from left to right. But I want to animate that sprite through various images so that it may look like a flying bird. I don't know how to accomplish that.

Here is my code:

    CCSprite *target = [CCSprite spriteWithFile:@"Target.png" rect:CGRectMake(0, 0, 27, 40)]
id actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(-target.contentSize.width/2, actualY)];
    id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)];
    [target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];

Solution

  • For Animating particular sprite You would require sprite-sheet to be there in your Resource. You can create the Sprite-sheet from eitherTexture Packer OR Zwoptex Tools which I normally use.

    Next you can implement the Below Code

        CCSpriteBatchNode *sheet = [CCSpriteBatchNode batchNodeWithFile:@"drawing1-i3.png"]; // Png File Name
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"drawing1-i3.plist"]; // Plist File Name
        [self addChild:sheet];
    
            //Generating the Animation 
        NSMutableArray *arr_anim =[NSMutableArray array];
        for(int i=1; i<30; i++) // i< number of frames in the plist File Name
        {
            NSString *str_fileNm = [NSString stringWithFormat:@"drawing1%d.png",i];
            CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache]spriteFrameByName:str_fileNm];
            [arr_anim addObject:frame];
        }
    
        CCSprite *startAnim = [CCSprite spriteWithSpriteFrameName:@"drawing11.png"];
        [startAnim setPosition:ccp(150,150)];
        [self addChild:startAnim];
    
        //Starting the Animation 
        CCAnimation *animation = [CCAnimation animationWithFrames:arr_anim delay:0.15f];
        // id action =[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:YES]];
        id action =[CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO];   
        [startAnim runAction:action];
    

    I think it would help you for creating the Animations.