1
votes

I'm learning SpriteKit and as an example I tried to add few SKSpriteNodes on the scene each with a label. Here is how my node graph should look (code sample is below):

Scene | +-- SpriteNode1 | | | +-- SpriteNode2 | +-- LabelNode1 | +-- SpriteNode2 | +-- SpriteNode3 +-- LabelNode2

According to the documentation from Apple SpriteKit should render SpriteNode1, then its children, then SpriteNode2 then its children. However the rendering result that I got clearly shows that SKLabelNodes are rendered after the other elements, so the label in the SpriteNode1 overlap label in SpriteNode2.

What I tried to achieve is to draw a simple playing card with text on it.

Here is what rendering result looks like:

rendering result

Here is a code snippet:

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

    [self addDummyNodeAt: CGPointMake(500, 500)];
    [self addDummyNodeAt: CGPointMake(550, 520)];
}

-(void)addDummyNodeAt: (CGPoint) point {
    // Create a sprite
    SKSpriteNode* sprite = [[SKSpriteNode alloc] initWithColor:[self getRandomColor] size:CGSizeMake(165, 220)];
    sprite.position = point;
    [self addChild:sprite];

    // Add another color rectangle as a node to a sprite
    SKSpriteNode * testNode = [[SKSpriteNode alloc] initWithColor:[self getRandomColor] size:CGSizeMake(120, 50)];
    testNode.position = CGPointMake(0, 0);
    [sprite addChild: testNode];

    // Add a text
    SKLabelNode *cardLabel = [SKLabelNode labelNodeWithFontNamed:@"Tahoma"];
    cardLabel.text = @"This is a text";
    cardLabel.fontColor = [SKColor blackColor];
    cardLabel.fontSize = 12;
    cardLabel.position = CGPointMake(-22, -70);
    [sprite addChild: cardLabel];
}

-(UIColor*) getRandomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
1

1 Answers

4
votes

In your view controller check that

skView.ignoresSiblingOrder = false

and you can set the

sprite.zPosition=1

to manually control the order the sprites are drawn in.