How to pause and resume in Cocos2d

2019-08-12 07:31发布

问题:

So my idea is have a special bullet that freezes the enemies, and after a period of time the enemies unfreeze itself and continue with their actions/animations. Here's a simple version of what I did:

-(void)update:(ccTime)dt
{
     CCSprite *enemySprite;
     CCARRAY_FOREACH(enemies, enemySprite)
     {
         if (CGRectIntersectsRect(_bullet.boundingBox, enemySprite.boundingBox))
         {
               _bullet.visible = NO;
               [enemySprite pauseSchedulerAndActions];
               enemySprite.pausingDuration = CACurrentMediaTime() +5;
         }
         if (CACurrentMediaTime() > enemySprite.pausingDuration)
              [enemySprite resumeSchedulerAndActions];
     }
}

Now, the problem I think I am encounter is that enemySprite has stop updating its scheduler here, so next time the update method is called the enemySprite that has been paused won't get update! I wish I knew a better way of explaining this, but I think any expert programmer would see what's wrong with this code immediately. Please help me out with suggestions to improve the code or even just an idea would be appreciated, thank you for your time.

回答1:

You called? :)

Yes, pauseSchedulerAndActions as well as Director's pause methods are both crappy ways of implementing pause because you have no control over what gets paused and what can continue to run (such as a pause menu layer perhaps).

In your case you can at least be more specific and for example only pause actions, but not scheduled updates:

[enemySprite.actionManager pauseTarget:enemySprite];

For more fine grained control it is recommended not to rely too heavily on scheduled methods in each object, instead have a central object (scene or layer) send all updates to its children - that way you can later decide more easily which children should continue to receive updates during pause.