Search code examples
objective-ccocos2d-iphoneccsprite

Multiple Sprite Actions


I am using Cocos2d engine and I've faced a strange problem.

I have a sprite. Also, I have 2 animations for that sprite. And I want to play one animation when app loads and second, after ccTouchevent is called.

walkAnim = [CCAnimation animation]; 
dropAnim = [CCAnimation animation]; 
for( int q=1;q<12;q++){
    [walkAnim addFrameWithFilename: [NSString stringWithFormat:@"walkforward_%.2d.png", q]];
    [dropAnim addFrameWithFilename: [NSString stringWithFormat:@"drop_%.2d.png", q]];
}
action = [CCAnimate actionWithAnimation:walkAnim];
action.duration = 2;
id act = [CCRepeatForever actionWithAction:action];
[sprite runAction:act];

So, here we see an animating sprite.

[sprite stopAllActions]; //and here my torture begins

I have tried many ways of creating an action:
I've tried to add another AnimateAction, tried to replace the current animation, but everything results in a crash.

[action setAnimation:dropAnim];

and

CCAnimate* animat = [[CCAnimate alloc]initWithDuration:30 animation:dropAnim restoreOriginalFrame:YES];

and

id action = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:dropAnim]];
[player1 runAction:action];

The crash is in [CCAnimate actionWithAnimation:]

+(id) actionWithAnimation: (CCAnimation*)anim
{    
    return [[[self alloc] initWithAnimation:anim restoreOriginalFrame:YES] autorelease];
}

Thanks!

To launch an action from another method, you have to retain the action
Eg: [action retain];


Solution

  • To launch an action from another method, you have to retain the action
    Eg: [action retain]; and then do not forget to release it

    -(void)create{
        for( int q=1;q<12;q++){
            [playerWalkAnim addFrameWithFilename: [NSString stringWithFormat:@"walkforward_%.2d.png", q]];
        }
        playerAction = [CCAnimate actionWithAnimation:playerWalkAnim];
        playerAction.duration = 2;
    
        [playerAction retain];
    }
    
    -(void)launch{
        [player1 runAction:playerAction];
    }