zPosition weirdness, parent node gets on top or below randomly

Hello, there,


I'm having this strange problem. I have a SKLabelNode as parent, and a SKSpriteNode as child, SKLabelNode's zPosition = 100, SKSpriteNode's zPosition = 0, the expected result is we see the label text on top of the SKSpriteNode. But when I run the code, sometimes the label node shows and sometimes doesn't(apparently goes under the child node). Here's my didMoveToView code in SKScene


override func didMoveToView(view: SKView) {
        let cloud = SKSpriteNode(imageNamed: "Cloud")
        cloud.position = CGPoint(x:0, y: 0)
        cloud.zPosition = 0

        let label = SKLabelNode(text: "this is a test")
        label.fontColor = UIColor.blackColor()
        label.fontSize = 40
        label.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGFloat(CGRectGetMidY(self.frame)))
        label.zPosition = 100
        label.addChild(cloud)
        self.addChild(label)
 }


This feels like a bug to me, but still I could be making some stupid mistakes somewhere. the reason I have SKLabelNode as parent other than other way around is because I want the SKLabelNode and SKSpriteNode moving together and if I set SKSpriteNode as parent, text on the label will blink when moving.


any help would be much appreciated,


Ron

Replies

I solved the issue by creating another NSSpriteNode as parent and add other 2 nodes to it.

Still, the displaying problem related to SKLabelNode as parent seems to be a bug


Ron

It's not a bug. The parent's zPosition is 100. The child's zPosition is (parent.zPosition + 0), so also 100. Nodes at the same zPosition are drawn in an unpredictable order.


The trick is to remember that child properties are computed relative to their parent (well, all their ancestors) but the result is an absolute. In this situation, making both parent and child subnodes of a SKNode (no need to create a SKSpriteNode) is acceptable, though of course they still need different absolute zPositions.


Keeping the current arrangement but setting the child zPosition to (say) 1 would also work here.