Tiddly
Tiddly

Reputation: 1620

Restarting an action in cocos2D for the iPhone

If I am using an action that does not repeat in cocos2D how do I restart that action?

I am using the code:

 CCAnimate* action = [CCAnimate actionWithAnimation:myAnimation];

 [mySprite runAction: action];

The action runs fine once, but when an event is triggered I want to be able to run the action again as long as it is finished, so I tried using this when the even is triggered.

 if( [action isDone] ){

     [mySprite runAction: action];

 }

But this results in a crash. Anyone any idea what the correct way to do this is?

Upvotes: 1

Views: 2391

Answers (3)

Rhuntr
Rhuntr

Reputation: 37

I had the same issue I declared CCAction* myAction in the header file but when i went to call it from another method i experienced a crash but like @Bongeh mentioned when using [myAction retain] it worked perfectly

Upvotes: 0

Tiddly
Tiddly

Reputation: 1620

Turns out I just wasn't retaining the action and the sprite must have been deleting it once it was done. So now my code is;

  CCAnimate* action = [CCAnimate actionWithAnimation:myAnimation];

  [mySprite runAction: action];

  [action retain];

and then when i want it to run again;

 if( [action isDone] ){

      [mySprite runAction: myAction];

 }

Upvotes: 0

Bongeh
Bongeh

Reputation: 2300

try preserving the action in an instance variable. In the header file have a pointer declared

CCAction* myAction;

then when the layer or sprite is initialized

myAction = [CCAnimate actionWithAnimation:myAnimation];

From what point on, whenever you want to call your action do

if( [action isDone] ){

 [mySprite runAction: myAction];

}

I think the reason your app is crashing is because you are calling an action that only exists for the duration of the method in which it is initialized.

Im my game i use CCSequences (so i can use CCCallFunc to set/declare variables mid animation), all these CCSequences are stored as instance variables in my CCSprite subclass.

I have an idle animation that repeats for ever.

Whenever I want to 'jump' for instance i call

[self stopAllActions];
[self runAction:jumpSeq];

My jumpSeq is a CCSequence that plays a jump animation, and has a CCCallFunc at the end of the sequence that restarts the idle animation when it is done.

Hope this helps.

Further reading: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:actions_special?s[]=cccallfunc

Upvotes: 2

Related Questions