Search code examples
iosobjective-ciphoneios7sprite-kit

How to get SKLabelNode score with image Numbers in spritekit


i am making a game with sprite kit for iphone. In the gameScene.m im adding score with image numbers so i can get the 1 and 2 digit score by the below 2 cases but i want to add 3 digit score in case3,please as me if u need to know more about this ask me before downgrading thanks.

 //int _gamescore;
_gameScore = 0;
_finalScore = [SKSpriteNode node];
 NSString *digit = [NSString stringWithFormat:@"%i",_gameScore];
[self setScore:(int)digit.length];

-(void)setScore:(int)numberofDigitsInScore
  {
    NSMutableString *scorestring = [NSMutableString stringWithFormat:@"%i", _gameScore];
    [_finalScoreSprite removeAllChildren];
    double val1;
    int sides;
     CGFloat y = self.size.height/2 -10;//position of score on screen

switch (numberofDigitsInScore) {
   case 1:      //  0-9 numbers
       {
           NSString *digit =[scorestring substringFromIndex:0];
           SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:[NSString      
           stringWithFormat:@"Number%@",digit]]; // Number(images 0-9 number images)
           sprite.position = CGPointMake(self.size.width/2, y );
           [_finalScore addChild:sprite];
           break;
       }

 case 2:     //   10-99 numbers
       {
        for (int i = 0; i < scorestring.length; i++) {
            sides =(i!=0)? 1 :-1;
            NSString *digit= [scorestring substringWithRange:NSMakeRange(i, 1)];
            SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:[NSString
             stringWithFormat:@"Number%i",digit.intValue]];

            if (digit.intValue == 1)
            {
                val1 = 5   ;
            } else{
                val1 = 0;
            }
            sprite.position = CGPointMake(self.size.width/2 + (17 -val1)*sides, y);
            [_finalScore addChild:sprite];
        }

        break;
}

Solution

  • An acute case of spaghetti code. Try to simplify. Eliminate cryptic variable names such as val1 or sides. You should not write the same code twice and you should generalize enough to work for any number of digits.

    CGFloat widthOfDigit = .... // figure this out beforehand. Include spacing.
    NSString *scoreString = [NSString stringWithFormat:@"%i", _score];
    CGFloat currentX = (self.size.width - (scoreString.length-1) * widthOfDigit) / 2.0
    for (int i=0; i<scoreString.length; i++) {
       NSString *digit = [scoreString substringWithRange:NSMakeRange(i,1)];
       SKSpriteNode *digitSprite = [SKSpriteNode spriteNodeWithImageNamed:
          [NSString stringWithFormat:@"Number%@",digit]];
       digitSprite.position = CGPointMake(currentX,y);
       [_finalScore addSprite:digit];
       currentX += widthOfDigit;
    }