views:

94

answers:

2

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?

+1  A: 

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

Bongeh
In my code I am storing the action as a class variable. I tried stopping all actions before calling runaction but it made no difference. I'm not entirely sure how I would use CCCallFunc with the way my code works.
Tiddly
try dropping a retain]; on the end of your action (remember to release it in your dealloc method though)
Bongeh
A: 

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];

 }
Tiddly