Search code examples
ioscocos2d-iphonecollision

Count Collision Cocos2d 3.0


How can i code collision count? So then it can be displayed as the score :D

This is my collision code

- (BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair monsterCollision:(CCNode *)monster projectileCollision:(CCNode *)projectile {
//Creating another sprite on the position the monster one was.
CCSprite *explosion = [CCSprite spriteWithImageNamed:@"explosion.png"];
explosion.position = monster.position;
[self addChild:explosion];

CCActionDelay *delay = [CCActionDelay actionWithDuration:.0f];
CCActionFadeOut *fade = [CCActionFadeOut actionWithDuration:.4f];
[explosion runAction:[CCActionSequence actionWithArray:@[delay,fade]]];

[monster removeFromParent];
[projectile removeFromParent];
return YES;

}

What would i add to count the collision of the Monster?

Thank you :)

New Code

CCLabelTTF *scorelabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"score: %d",score] fontName:@"Verdana-Bold" fontSize:18.0f];
scorelabel.positionType = CCPositionTypeNormalized;
scorelabel.color = [CCColor blackColor];
scorelabel.position = ccp(0.85f, 0.95f); // Top Right of screen
[self addChild:scorelabel];

Solution

  • Declare an attribute on the class to count times of the collision.

    int score;
    

    Then on your init method set it to zero

    int score=0;
    

    And finally each time collision happens increment the value by one as.

    - (BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair monsterCollision:(CCNode *)monster projectileCollision:(CCNode *)projectile {
    //Creating another sprite on the position the monster one was.
    CCSprite *explosion = [CCSprite spriteWithImageNamed:@"explosion.png"];
    explosion.position = monster.position;
    [self addChild:explosion];
    
    CCActionDelay *delay = [CCActionDelay actionWithDuration:.0f];
    CCActionFadeOut *fade = [CCActionFadeOut actionWithDuration:.4f];
    [explosion runAction:[CCActionSequence actionWithArray:@[delay,fade]]];
    score++;
    
    [monster removeFromParent];
    [projectile removeFromParent];
    return YES;
    
    }