How do you implement hierarchical render order in an entity system?

For example: two player entities each carry a gun entity. If you set the player entities to zindex = 0 and the gun entities to zindex = 1, then player 1 might render behind player 2 but his gun will render in front of player two.

I'm migrating a game from a scene-graph system where the order is self-evident from the parent/child relationship. The only way I can see of achieving the above is to simulate that parent/child relationship by giving every entity its own reserved range of z-indexes like so. player1 z=0 player1-gun z=1 ... player2 z=5 player2-gun z=6

This would require some kind of auto assignment system. Is this how it's done or is there some pattern I'm missing?


There isn't one way that "it's done," really; it sounds like you may be coupling you renderer and your entity system too tightly together (generally they don't really need to know about eachother). However, it seems like a straightforward solution to your problem is to introduce hierarchy to the appropriate components.

Presumably the gun entity has either a transform component or a visualization component with transform information. Or perhaps tranformation is considered important enough to be a first-class property of an entity in your system.

In any case, add the notion of a parent reference to whichever aspect of your system has the transformation information. They you can recover the Z order information you need from that hierarchical structure, just like you would in a graph system:

Order your top level components by whatever predicate you consider appropriate to break Z-order ties (such as by their screen height). Assign the first component the next available Z index, and then assign successive Z indices to its children before moving on to the next top-level component.

This will not solve every possible problem, but it will put you back into the same problem space as a graph-based solution.

  • \$\begingroup\$ Ah yes I get you. I've been looking at the Unity Transform component but it hadn't occurred to me to use it as the sorting order. I can't visualise exactly how I'm going to work it yet but it gives me a line of study. Thanks Josh. \$\endgroup\$ – Octothalamus Mar 25 '15 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.