Search code examples
objective-csprite-kitsklabelnode

SpriteKit displaying variable number


What is the best way to display some value (that changes as the game runs) on the screen in iPhone SpriteKit? The only way I can think of is SKLabelNode, but it's probably not meant to be used like this and also I can't find any way to measure its width, which makes me unable to position it correctly (I want it to be in the bottom right corner). Thanks in advance :).

@Edit

My attempt at doing this:

 SKLabelNode *someLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];

 someLabel.text = some_string;
 someLabel.fontSize = 30;
 someLabel.fontColor = [SKColor blackColor];
 someLabel.position = CGPointMake(some_int, 15);

 [self addChild:someLabel];

The values of some_string and some_int change as the game runs, so someLabel is removed, someLabel.text and someLabel.position are re-assigned, and the label is added again. Yes, I am aware that this is a bad way to do this...


Solution

  • Unfortunately, SKLabelNode is your simplest bet, it's just not the most robust tool. You just want to update its text and its position when you need to. Your code is correct, and if you want to get its actual size, then you would get the width of its frame.

    update text:

    someLabel.text = theNewText;
    

    update position:

    someLabel.position = theNewPosition;
    

    get relative width

    float widthOfLabelFrame = someLabel.frame.size.width;
    

    additional alignment settings that might help (vertical baseline is the default):

    someLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeRight;
    someLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeBaseline;