Search code examples
iosobjective-csprite-kitskscene

Error in updating the score in a game


I have problem when i updating score in the game i make i dont know what is the problem but when i shoot something the score should increment by 1 but in my code sometimes it increment by 2 or 3 sometimes 1 it not constant i dont know why this happen here is the code i used

@interface GameScene () {

    SKLabelNode* _scoreLabelNode;
    NSInteger _score;


}


-(void)didMoveToView:(SKView *)view {

    _score = 0;
        _scoreLabelNode = [SKLabelNode labelNodeWithFontNamed:@"Silom Regular"];
        _scoreLabelNode.fontSize = 50;
        _scoreLabelNode.position = CGPointMake(self.size.width - 335 , self.size.height - 60);
        _scoreLabelNode.zPosition = 100;
        [self addChild:_scoreLabelNode];

        _scoreLabelNode.text = [NSString stringWithFormat:@"%d",_score];
}

if (contact.bodyB.categoryBitMask == ObjectCategory) {

        _score++;
        _scoreLabelNode.text = [NSString stringWithFormat:@"%d",_score];
}

Solution

  • There are few similar issue with this delegate, see if this may fix your issue:

    SpriteKit: didBeginContact being called non-stop on iPad

    Why are didBeginContact called multiple times?

    didBeginContact is being called multiple times for the same SKPhysicsBody

    Even if it doesn't solve your problem, you can use a flag variable to handle this score update for once. e.g.,

    bool hasScoreUpdated;
    
    - (void)didBeginContact:(SKPhysicsContact * _Nonnull)contact
    {
        if(!hasScoreUpdated)
        {
            _score++;
            hasScoreUpdated = true;
        }
         // your rest of the logic
    }
    
    - (void)didEndContact:(SKPhysicsContact * _Nonnull)contact
    {
        hasScoreUpdated = false;
    }
    

    EDIT:

    Based on your comment above:

    i put "NSLog (@"%d", _score )" after "_score++" it increment as should like 10 11 12 .. etc but the score jumped from 10 to 12

    It is possibly due to the very frequently calling the respective event and a very rapidly update of UI element.