Search code examples
iphonecocos2d-iphoneccsprite

CGRectIntersectsRect condition is true calls multiple times


I'm new to cocos2D , I have problem in detect collision method , the CGRectIntersectsRect is true even the object is removed, after the collision and need to show 100+ texted CCLabelTTF once , but it is add multiple times. below the Code

-(void)detectBonousPtCollision
{  
   for (CCSprite *sprite in pointsArray)
   {
       NSLog(@"tag value  %d",sprite.tag);
       if (CGRectIntersectsRect(playerSprite.boundingBox, sprite.boundingBox))
      {

         [self removeChild:sprite cleanup:YES];
         [label setString:[NSString stringWithFormat:@"score %d",totalScore = totalScore+100]];

         CCLabelTTF *ptLabel = [CCLabelTTF labelWithString:@"100+" fontName:@"Marker Felt" fontSize:20];
         ptLabel.position = ccp(playerSprite.position.x, playerSprite.position.y);
         ptLabel.tag = 102;
         [self addChild:ptLabel];

         CCSequence *sequence = [CCSequence actions:
                                [CCMoveTo actionWithDuration:3 position:ccp(playerSprite.position.x+10, playerSprite.position.y+10)],
                                [CCCallFunc actionWithTarget:self selector:@selector(afterAnimation:)],
                                nil];

         [ptLabel runAction:sequence];
         //[[SimpleAudioEngine sharedEngine] playEffect:@"CrashSound.wav"];
      }

   }
}

Please help.


Solution

  • remove sprite from your array too and add break in your if statement

    if (CGRectIntersectsRect(playerSprite.boundingBox, sprite.boundingBox))
    {
        [pointsArray removeObject:sprite];
        [self removeChild:sprite cleanup:YES];
        [label setString:[NSString stringWithFormat:@"score %d",totalScore = totalScore+100]];
    
        CCLabelTTF *ptLabel = [CCLabelTTF labelWithString:@"100+" fontName:@"Marker Felt" fontSize:20];
        ptLabel.position = ccp(playerSprite.position.x, playerSprite.position.y);
        ptLabel.tag = 102;
        [self addChild:ptLabel];
    
        CCSequence *sequence = [CCSequence actions:
                                [CCMoveTo actionWithDuration:3 position:ccp(playerSprite.position.x+10, playerSprite.position.y+10)],
                                [CCCallFunc actionWithTarget:self selector:@selector(afterAnimation:)],
                                nil];
    
        [ptLabel runAction:sequence];
        //[[SimpleAudioEngine sharedEngine] playEffect:@"CrashSound.wav"];
        break;
    }