我的场景中有两个父SKNode,其zPosition为1(node1)和2(node2).我想要实现的是node2应始终分层ABOVE node1.但不幸的是,node1的子节点(其zPosition为1-50)都位于node2的子节点之上(当前没有zPosition).有没有办法解决这个问题(除了给node2一个超过50的zPosition)?也许是某种布尔参数来设置所有子节点的zPosition相对于它的父节点?任何帮助将不胜感激!
编辑:为了更清楚,这里是所有元素的层次结构:
> node1:SKNode(zPosition 1)
> child1:SKNode(zPosition 1)
> child2:SKNode(zPosition 2)
> child3:SKNode(zPosition 3)
> ……
> child50:SKNode(zPosition 50)
> node2:SKNode(zPosition 2)
> child1:SKLabelNode(没有zPosition)
> child2:SKLabelNode(没有zPosition)
> child3:SKLabelNode(没有zPosition)
> ……
> child50:SKLabelNode(没有zPosition)
EDIT2:这是我的GameScene类的一个非常简化的版本:
import SpriteKit class GameScene: SKScene { let gameNode = SKNode() let node1 = SKNode() let node2 = SKNode() let nodeSize:CGFloat = 50.0 let spacing:CGFloat = 5.0 required init(coder aDecoder: NSCoder) { fatalError("NSCoder not supported") } override init(size: CGSize) { super.init(size: size) self.addChild(gameNode) node1.name = "node1" node2.name = "node2" node1.zPosition = 1 node2.zPosition = 2 gameNode.addChild(node1) gameNode.addChild(node2) // add children to node1 for i in 1..<10 { let child = SKSpriteNode(color: UIColor.redColor(),size: CGSize(width: nodeSize,height: nodeSize)) child.position = CGPointMake((nodeSize + spacing) * CGFloat(i),0) child.zPosition = CGFloat(i) self.node1.addChild(child) } // add children to node2 for i in 1..<10 { let child = SKLabelNode(fontNamed: "Avenir Black") child.position = CGPoint(x: (nodeSize + spacing) * CGFloat(i),y: 0) child.text = "label\(i)" child.fontSize = 10 child.fontColor = UIColor.blackColor() self.node2.addChild(child) } } }
运行它时,您可以看到只有node2(label1)的第一个子节点位于node1的第一个子节点之上(因为它们具有相同的zPosition).所有其他的都在node1的子节点下面.
Maintaining the order of a node’s children can be a lot of work. Instead,you can give each node an explicit height in the scene. You do this by setting a node’s zPosition property. The z position is the node’s height relative to its parent node,much as a node’s position property represents its x and y position relative to parent’s position. So you use the z position to place a node above or below the parent’s position.
When you take z positions into account,here is how the node tree is
rendered:
- Each node’s global z position is calculated.
- Nodes are drawn in order from smallest z value to largest z value.
- If two nodes share the same z value,ancestors are rendered first,and siblings are rendered in child order.
我发现 – 我不知道它是这样的 – 是孩子zPosition计算总结他们的父母zPosition,所以如果node1.zPosition(node1的)child3.zPosition = 4,和node2.zPosition(node2的)child3 .zPosition = 3,node1的孩子将被涂在上面.
解决方案:将node2.zPosition设置为大于(node1)的lastChild.zPosition node1.zPosition.