How to bring a SKSpriteNode to front?

前端 未结 4 970
悲&欢浪女
悲&欢浪女 2021-01-03 18:26

How can I bring a SKSpriteNode to the front of all other node?

With UIView, I can use bringSubviewToFront to bring an uiview in front of other views.

相关标签:
4条回答
  • 2021-01-03 18:35

    You can't "bring it to front" but you can change the zPosition of it.

    The higher the zPosition of the node the later it gets rendered.

    So if you have three nodes with zPositions of -1, 0 and 1 then the -1 will appear at the back. Then the 0. Then 1 will appear at the front.

    If they all use the default zPosition of 0.0 then they are rendered in the order they appear in the children array of the parent node.

    You can read it all in the docs.

    https://developer.apple.com/documentation/spritekit/sknode

    0 讨论(0)
  • 2021-01-03 18:38

    If you want to bring a node to the very front use this:

    yourNode.zPosition = 1

    or to the very back:

    yourNode.zPosition = -1

    or the same level as other nodes(as it's set to this value by default):

    yourNode.zPosition = 0

    0 讨论(0)
  • 2021-01-03 18:40

    This extension adds a bringToFront method to SKNode. This great for times when zPosition is inappropriate, and you want to rely on sibling ordering.

    extension SKNode {
        func bringToFront() {
            guard let parent = parent else { return }
            removeFromParent()
            parent.addChild(self)
        }
    }
    

    `

    0 讨论(0)
  • 2021-01-03 18:45

    SWIFT 4: I usually create enums to establish zPositions, so I can simply manage the different layers:

    enum ZPositions: Int { case background case foreground case player case otherNodes }

    • “case background” is the lower position, it’s equal to the default position of 0;
    • “case foreground” = 1
    • “case player” = 2
    • “case other nodes” = 3

    So, when you setup a new item, you can give it the zPosition simply this way:

    button.zPosition = CGFloat(ZPosition.otherNodes.rawValue)

    (button now has the highest zPosition) Hope it helps...

    0 讨论(0)
提交回复
热议问题