Search code examples
cocos2d-iphonegame-physicsspritebuilder

It seems, that method is called twice, when collision happens . cocos2d-iphone


I use this code to show game over menu after _hero sprite and _enemy sprite collide :

if (CGRectIntersectsRect(_hero.boundingBox,_enemy.boundingBox)) {
    CCActionCallFunc *_callShowMenu=[CCActionCallFunc actionWithTarget:self selector:@selector(showMenu)];
    [self runAction:_callShowMenu];

   // EDIT : I also remove both sprites when collision happens.

   [_hero removeFromParent];
   [_enemy removeFromParent];
}

In _callShowMenu I just stop all actions and show a sprite with half transparent black background image and buttons. Sometimes when collision happens, it seems to me, that _callShowMenu is called twice, because background is completely black, like there is the same image behind. Has anyone had a similar problem? (Mostly background image is half-transparent, as it should be).

EDIT:

-(void)showMenu{
   [[CCDirector sharedDirector] pause];
    CCSprite *_halfTransparentBackground=[CCSprite spriteWithImageNamed:@"halfTransparentBackground.png"];
    _halfTransparentBackground.position=ccp(160, 280);
    [self addChild:_blackBack z:5]; 


}

Solution

  • I found a solution using BOOL. Actually everyone uses BOOL in this case, so I don't need to reinvent the wheel.

    BOOL doNotCallMeTwice;
    

    Somewhere in the didLoad method:

     doNotCallMeTwice=NO;
    

    In the collision detection method:

    if (doNotCallMeTwice==NO) {
                  [self showMenu];
            }
    

    And finally:

    -(void)showMenu{
     doNotCallMeTwice=YES;
    }
    

    Possibly, showMenu was called twice(or much more times),because collision detection is in the update method.