Merge Sprites: Z-Index VS Layers

I have a game object with two sprites:

  • the main character
  • an additional helmet

If both sprites have the same z-index, the helmet appears under the main character. (Is there a way to change the order?)

If I increase the z-index of the helmet, the result is as expected BUT if two enemies run into each other one of them appears to be between the character and the helmet of the other one.

How can I achieve the expected output (both sprites get treated as ONE sprite)?
To rephrase the question: How can I merge the sprites?

1 Like

I think your best bet is to explicitly pick different z-planes for each enemy otherwise you’re saying “I don’t care” which really mean “Let the computer decide randomly which one gets drawn when”.

That’s what’s leading to your enemy/hat-swapping: enemy-1 is drawn first and then enemy-2 (since they’re on the same z-plane), then helmet-1 (which now looks like it’s on enemy-1). Maybe sometimes you get lucky and enemy-2 is drawn first and then enemy-1, then helmet-1 (and now enemy-1/helmet-1 look correct). The only way to avoid that is to define the order you want them drawn by choosing the z-index for each piece.

If you don’t have too many enemies, you could maybe just define N z-planes and use one per enemy?

(all of this is assuming you need the helmet as a separate thing, maybe it’s enabled/disabled for different enemies; you could always just “merge” the sprites together in a graphics program)

The problem is: It’s all the SAME enemy. I spawn multiple instances of it using a factory.

So what you propose is basically something like

  1. Set z-index on spawn and store the information in a table
  2. On the next spawn use a z-index that is not already in the table
  3. If enemy dies, remove the associated z-index references from the table

I can do that but I’d prefer something like a parent sprite that holds all children (in my case the character and the hat) and then I can change the drawing order (e.g. by setting the z-index) of the children without affecting the z-index of the parent sprite.

In GIMP or Photoshop I can easily merge the main character and the hat to one sprite. Something like that should also be possible in Defold IMHO.

This is not a fair comparison. GIMP and Photoshop are raster image editors, not game engines. You can’t easily achieve this in any game engine.

I don’t think it’s possible to do this using the same Z value. If two sprites share the same Z, it can cause something called Z-fighting, where one of them (usually at random) appears on top of the other. This is expected behavior in all game engines.

One option that comes to mind is to use a separate render target for those items and render them there. You’ll need to come up with your own workaround to achieve this effect.

2 Likes

Thank you for the explanation. Makes totally sense!

1 Like