Search code examples
objective-csprite-kitpositionskshapenodesklabelnode

Positioning sprites relative to their parent


-(void)drawGUIForPlayer:(PlayerClass *)player {

    SKShapeNode *outlineBox = [SKShapeNode shapeNodeWithRect:CGRectMake(0, self.view.frame.size.height - 60, 150, 30)];
    outlineBox.fillColor = [SKColor colorWithRed:0 green:0 blue:1 alpha:0.3];
    outlineBox.strokeColor = [SKColor clearColor];
    [self addChild:outlineBox];

    SKLabelNode *playerName = [SKLabelNode labelNodeWithText:player.name];
    playerName.color = [SKColor colorWithWhite:1 alpha:0.5];
    playerName.fontSize = 10;
    [outlineBox addChild:playerName];
    [playerName setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeCenter];
    [playerName setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];

}

Previously, I would create such a technique to say add a box, then put the label as child of the box. Essentially making the box a view so I could position the label relative to the shapenode. However, with this I'm getting a position of 0,0 which positions it relative to the self.view as opposed to the outlineBox.view.

Can anyone point me in the right direction?


Solution

  • I think you perhaps misunderstand what [SKShapeNode shapeNodeWithRect:CGRectMake(0, self.view.frame.size.height - 60, 150, 30)] is doing.

    As per Apple Documentation https://developer.apple.com/reference/spritekit/skshapenode/1520047-shapenodewithrect?language=objc:

    A rectangle, relative to the node’s origin.

    Your outlineBox is not "centered" it's parent.

    outlineBox's parent is self. playerName's parent is outlineBox. As you have not adjusted any transforms on outlineBox it will appear as if it is relative to self.

    Note you should not be referring to SKNode as having a view. They do not.