Search code examples
swiftsprite-kitspriteskspritenodescene

SpriteKit: Node On Top Of Another Node


I want to create my player on top of the background. Somehow this doesn't work. The node counter goes up by one but it isn't visible. I do add the player after I add the background so it should be on top. The code I use to create the player:

var player = SKSpriteNode()

func addPlayer(gameScene: GameScene, xPos: CGFloat, yPos: CGFloat){
    player = SKSpriteNode(imageNamed: "player")
    player.size = CGSize(width: fieldsWidth, height: fieldsWidth)
    player.position = CGPoint(x: xPos, y: yPos)
    gameScene.addChild(player)
}

And I access the function from another class like this:

        person().addPlayer(self, xPos: fieldsWidth/2, yPos: fieldsWidth/2)

Hopefully you can help me.


Solution

  • If you are sure that you have added node at desired position, which is probably the situation here because node count is incremented, you can set player's and background's zPosition to make player above the background:

    var player = SKSpriteNode()
    
    //1. somewhere in your code set background's zPosition to 1 before you add it to the scene
    
    func addPlayer(gameScene: GameScene, xPos: CGFloat, yPos: CGFloat){
        player = SKSpriteNode(imageNamed: "player")
    
        //2. Set player's zPosition to be higher than background's zPosition
        player.zPosition = 2 
        player.size = CGSize(width: fieldsWidth, height: fieldsWidth)
        player.position = CGPoint(x: xPos, y: yPos)
        gameScene.addChild(player)
    }
    

    About ignoresSiblingOrder...I would recommend you to leave that to true because it can help a lot when it comes to performance . The only "thing" about this kind of optimization is that you have to explicitly set zPosition for nodes at same zPosition which can overlap, but you don't want to let them overlap in random order (which ignoresSiblingsOrder does when set to true), but rather to overlap in determined order (controlled by you). This is from docs:

    When this property is set to YES, the position of the nodes in the tree is ignored when determining the rendering order. The rendering order of nodes at the same z position is arbitrary and may change every time a new frame is rendered.

    So, just set zPosition explicitly and you will be fine.