37

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.

Phuong Ly
  • 383
  • 1
  • 3
  • 4

4 Answers4

59

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • 1
    Thank you for helping. This is what I need. Now I can bring SKSpriteNode to the front of background. – Phuong Ly Oct 03 '13 at 09:38
  • 2
    you could also create 2 layers (or more). have one for the background, and the other for the players etc. The order you add these will affect layering, so add the background layer first. – DogCoffee Oct 04 '13 at 22:15
5

SWIFT 4
I usually create enums to establish zPositions so that 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)

DaniChi
  • 301
  • 3
  • 12
1

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)
    }
}

`

Graham Perks
  • 23,007
  • 8
  • 61
  • 83
  • It doesn't seem like this would bring it to the front if the parent already has other child nodes that have a higher zPosition. Doesn't it default to a Position of 0.0? – bhause Dec 13 '22 at 22:28
  • As the comment says, this is for times when zPosition isn't appropriate for some reason. – Graham Perks Dec 14 '22 at 18:27
0

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

emido333
  • 144
  • 4
  • Not entirely true. #1 - This assumes nothing has a zPosition higher than 1, #2 - If you set multiple nodes to zPosition 1, then this doesn't decide which node is brought "to the very front". I recommend deleting this answer. – Tyler A. Jan 02 '21 at 17:01