Search code examples
xcodespritemovebackscene

Xcode GameScene.sks bringing sprites to front


I feel like this question is very simply resolved, but I can't for the life of me figure out a way to do it.

I have 4 sprites of equal size, all at the same coordinates in my GameScene.sks, 0,0. I know that I can select them with the menus on the left and on the top, but I really need to have certain sprites obscure others and have those others be obscured by the sprite in front of them. There are the options for "Bring to front" and "Push to back" when right-clicking on the currently visible sprite in the scene and also in the "Editor" tab on the top of my screen. But whenever trying to use these, absolutely nothing appears to happen. They're not greyed out, I just click on them as if they should be functioning and all my sprites remain in the same order.

If anyone knows what I'm doing wrong, I'd be very appreciative. Thanks in advance.


Solution

  • I'm not sure I understand your question fully.

    Are you saying you want to be able to set which sprite appears on top, which is below that, below that, and on bottom?

    If so, that is very easily done by changing the sprites zPosition

    let sprite1 = SKSpriteNode()
    let sprite2 = SKSpriteNode()
    let sprite3 = SKSpriteNode()
    let sprite4 = SKSpriteNode()
    
    sprite1.position = CGPoint(x: 0, y: 0)
    sprite2.position = CGPoint(x: 0, y: 0)
    sprite3.position = CGPoint(x: 0, y: 0)
    sprite4.position = CGPoint(x: 0, y: 0)
    
    //Bottom
    sprite1.zPosition = 1
    sprite2.zPosition = 2
    sprite3.zPosition = 3
    sprite4.zPosition = 4
    //Top
    
    self.addChild(sprite1)
    self.addChild(sprite2)
    self.addChild(sprite3)
    self.addChild(sprite4)
    

    zPosition can also be edited in the Attributes Inspector if you are using the GameScene to create nodes.

    zPosition