enumssprite-kitzposition

enum and zPosition problems in spriteKit


I am having some problems with enum used for establish zPositiion in sprite Kit. Here is the enum:

enum Layer:CGFloat {
   case Sky = 0
   case Clouds = 1
   case Background = 2
   case Foreground = 3
   case Character = 4
   case Foreground1 = 5
}

And then I am dividing my scene in different layers to include extra effects. I added worldNode as a spriteKit base node and then their children like this:

let backGroundMountain = SKSpriteNode(imageNamed: "Scene3BackgroundMountain1")
  backGroundMountain.zPosition = Layer.Background.rawValue
  worldNode.addChild(backGroundMountain)

let backGroundMountainOver = SKSpriteNode(imageNamed: "Scene3BackgroundMountainOver1")
  backGroundMountainOver.zPosition = Layer.Foreground.rawValue
  worldNode.addChild(backGroundMountainOver)

let greenCircle = SKSpriteNode(imageNamed: "green_circle_1")
  greenCircle.zPosition = Layer.Character.rawValue
  backGroundMountainOver.addChild(greenCircle)

let foreGroundMountainRight = SKSpriteNode(imageNamed: "Scene3FrontMountain1")
  foreGroundMountainRight.zPosition = Layer.Foreground1.rawValue
  worldNode.addChild(foreGroundMountainRight)

As you can see, greenCircle is a child of backGroundMountainOver while foreGroundMountainRight is a child of worldNode. I require this for the effects I mentioned before.

The problem is that although zPosition of foreGroundMountainRight is bigger that zPosition of greenCircle, the last one appears over the first. The only way to solve the problem is to change:

… case Foreground1 = 7

I don’t understand what is this happening.


Solution

  • This happens because you add the greenCircle Node (zIndex 4) on a node which already is in zIndex=3 (backGroundMountainOver) giving a total of zIndex 7. When the foreGroundMountainRight which is attached to the world node (I assume default zIndex = 0) is on zIndex = 5.