[SOLVED] Add sprite to a specific TMXLayer

Hi, I’m having trouble adding sprites to a TMXTiledMap, and having them preserve the Z index/order I add them with. Instead, it seems that the actual order in the code (meaning when in the code they are added), seems to dominate. I was wondering 1) if there is a solution to add the sprite to a specific layer, since the addChild method in TMXLayer is not allowed… 2) what is the reason to not allow this? Thanks in advance.

//
// Override
//
/** TMXLayer doesn’t support adding a Sprite manually.
@warning addChild(z, tag); is not supported on TMXLayer. Instead of setTileGID.
*/
using SpriteBatchNode::addChild;

I think I have found a solution, instead of adding sprites to a specific layer, I am reordering now the layers with the global Z order, so a given sprite could have Z order 1, the map order 2 and a given layer Z order 3, so the tiles in that layer will be on top of the sprite and so on:

this->addChild(this->sprite, 1);
this->addChild(this->map, 2);
this->map->getLayer("layer")->setGlobalZOrder(3);

Could you confirm whether this is a good solution? and also, I am still curious about the original question, just would be good to know the reason why that is designed that way… :slight_smile: Thanks!

The reason it’s not allowed is because the tilemap layers are rendered using batching. I believe SpriteBatchNode in the TMXLayer and primitive batching in FastTMXLayer.

If your map is isometric then another solution would be to use the depth buffer with a z-coordinate of the ‘3D’ position.

Another possibility is if you add your sprite textures into the layer’s associated tile sprite sheet texture atlas then you could look into merging them into the layer, though that would likely require some custom code to behave correctly.

A last option is to ditch the TMX tile map classes and write your own tile map renderer. This is actually easier than it sounds and makes sense if you’re working on a longer-term project. You could still use the Tiled map editor and write or find a parser, or only use the TMX parsing/import functionality.