Cocos2d – Working with Z Order, How does it work?

Today I solved a problem that I was having with z order properties for sprites in cocos2d.

Coming from a background developing applications for, it’s fairly common practice that all display objects are assigned a “Depth” that automatically iterates as children are added to the display list.  So the first element becomes assigned a depth of 0, the second is assigned 1, and the third assigned 2.

So armed with that back history, I looked at the zOrder property of CCSprite.

Ok, I thought, to move something to the first z order within a layer I can just set the zOrder to zero:

[myLayer reorderChild:mySprite z:0];

No dice. I googled, and all of the samples just said “reorderChild to z of 0”.  So either nobody has really done this, or I am missing the boat.

It appears that unless you add the z: parameter when adding a child to a parent, the z defaults to 0.  Moving another object to 0, where it already was, does nothing.

The easiest option to get something behind other elements, is to assign a negative z value below the 0 default:

[myLayer reorderChild:mySprite z:-1];

To move something in front of all other elements, assign a positive z value above the 0 default:

[myLayer reorderChild:mySprite z:1];

I hope this helps.

3 Comments on “Cocos2d – Working with Z Order, How does it work?

Leave a Reply

Your email address will not be published. Required fields are marked *