App Development » How to reorder sprites (CCSprite) zindex/zorder in Cocos2d

How to reorder sprites (CCSprite) zindex/zorder in Cocos2d

So I found myself with multiple sprites not knowing when they were stepping on top of each other. We don’t want that do we? Here’s a quick solution, and for a small project without a ton of sprites it seems to do the trick just fine without any noticeable performance hits.

Just put the following in your tick or update (or wherever you loop through all your sprites).

int newZ = (sprite.position.y * -1) + 1000;
[self reorderChild:sprite z:newZ];

A little explanation, all this does is set the sprites zOrder based on it’s position.y, we multiply it by -1 to make it negative and then add 1000 because the position.y is calculated from bottom to top and we want our lower positioned sprites to take on a greater zOrder value.

Hope that helps! If you have another solution please share it below!

Comments