Z depth and layers

Z depth and layers
0.0 0


Hi, i would like to know if my understanding of z-order and layers is correct (this are probably trivial considerations/questions but i am
a newbie with cocos2d-x :slight_smile:

z-order is used by cocos2d to sort sprites to be rendered. So, if i have two sprites A and B, with A having z-order of 0
and B z-order of 1, cocos2d render A first, then B.

If this is correct, i can obtain the same result using two layers, L0 with z-order 0 and L1 with z-order of 1. I could simply
add sprite A to L0, setting the A z-order to 0, and sprite B to L1, setting its z-order to 0. Then, since layer L0 get drawn before L1, A gets drawn before B.

If my understanding is correct, i would like to know what are the best practice. I mean, why i should use more layers if i can use the z-order?
My answers: using two layers i can:

  1. scroll L0 and not L1. this way all childs of L0 are subject to scrolling, while all childs of L1 not. This is easily accomplished managing L0.
    Using the z-orders and a single layer, i have to scroll all z=0 childs manually.

  2. using two layers, i can add at runtime elements betwen the two layers easily. For example, let L0 have z=0 and L1 z=1.
    If i want to add, at run-time, sprites between L0 and L1, i could easily change z order of L1 to 2 and add another layer at z=1.
    using only one layer, i have to change all z-order of nodes with z=1 to z=2…

That is, layers group sprites togheter, and they let create a z-ordering between group of layers.

I would like to hear other reasons to use multiple layers instead of only one. Your experience is welcomed!



I believe that your L0 sprites would always be drawn behind L1 sprites when using two layers + draw order. L0 drawn then L1 drawn. If you ever require an L0 sprite to be drawn in front of L1 then you would have to redraw or change to using VertexZ + alpha blending. You may want to check out the Parallax test in the tests folder.