Search code examples
animationcocos2d-iphoneccspritesprite-sheet

Cocos2D - When I animate second sprite, first stops animating


So the issue here is when I create one animated projectile, everything is fine. As soon as the user creates a second, the first stops animating.

Alright, here's how I'm setting it up in my init:

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:
     @"acorns.plist"];

CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode 
                                      batchNodeWithFile:@"acorns.png"];
[self addChild:spriteSheet];

NSMutableArray *flyingFrames = [NSMutableArray array];
    for(int i = 1; i <= 4; ++i) {
        [flyingFrames addObject:
         [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
          [NSString stringWithFormat:@"acorn%d.png", i]]];
    }

CCAnimation *flying = [CCAnimation 
                                 animationWithFrames:flyingFrames delay:0.5f];

self.flying = [CCRepeatForever actionWithAction:
                   [CCAnimate actionWithAnimation:flying restoreOriginalFrame:NO]];

Then, in my create bullets method which is called when the user taps the screen, I do:

CCSprite *bullet = [CCSprite spriteWithSpriteFrameName:@"acorn1.png"];
bullet.position = CGPointMake(140.0f, FLOOR_HEIGHT+145.0f);
[bullet runAction:_flying];

[self addChild:bullet z:9];
[bullets addObject:bullet];

So the first time the user taps, everything works fine. The second time, an animated bullet is created, but the existing one stops animating, and so on.


Solution

  • I believe each sprite should have its own actions, ie you cant reuse an action while the action is in progress. Something like:

    CCSprite *bullet = [CCSprite spriteWithSpriteFrameName:@"acorn1.png"];
    bullet.position = CGPointMake(140.0f, FLOOR_HEIGHT+145.0f);
    id _fly=[CCAnimation animationWithFrames:flyingFrames delay:0.5f];
    id _flyForever = [[CCRepeatForever _fly];
    [bullet runAction:_flyForever];
    [self addChild:bullet z:9];
    [bullets addObject:buller];
    

    The flyingFrames can be referenced by multiple animations, so you must take care of retaining the array for reuse.