Wait till all CCActions on different CCSprites are complete
-
22-07-2021 - |
Question
I am developing a simple cocos2d game in which I want to animate two CCSprite
s simultaneously, and for this purpose I simply set CCAction
s on respective `CCSprite's as follows.
[first runAction:[CCMoveTo actionWithDuration:1 position:secondPosition]];
[second runAction:[CCMoveTo actionWithDuration:1 position:firstPosition]];
Now I want to wait till the animations are complete, so I can perform the next step. How should I wait for these animations to finish?
There are actually two method calls, the first one animates the objects via the code above and second call does the other animation.
I need to delay the second method call until the animations in first are complete. (I would not like to use CCCallBlock
blocks as I want to call the second method from the same caller as the first one.
EDIT
I tried this ..
__block BOOL moving = YES;
[second runAction:[CCSequence actions:[CCMoveTo actionWithDuration:1 position:firstPosition], [CCCallBlockN actionWithBlock:^(CCNode *node){
CCLOG(@"\n\n\n\n\n\n\n\nMovement Finished\n\n\n\n\n\n\n\n");
moving = NO;
}],nil]];
while(moving);
But the CCCallBlock
never gets called thus forever stuck in while
loop =/
Solution
If I wouldn't dig it out of cocos's docs, I would implement my own observer object, to observe if a group of animations have been finished. It will require few quick steps:
- Create your own class like
PendingOperationsCounter
- Instantiate object of
PendingOperationsCounter
- Register finish action for this particular
PendingOperationsCounter
- Register every starting animation to your
PendingOperationsCounter
, when registering increase pending operations counter - When animation finishes it decreases operations counter
- If counter is zero again, it fires its own finish action you've registered
Done!
OTHER TIPS
Instead of a simple CCMoveTo in first, use a CCSequence with 1) the MoveTo, and 2) a CallBlock to start second. In the call block to start second, use again a CCSequence for 1) the moveTo, and 2) call a selector to do whatever you want to do. It will work in THIS use case. For a more generic approach, follow the above answer as a guideline.