For the past two months or so, I've been working on building a full game from my recent Ludum Dare entry, Celebration of Jand. For the most part, everything has been smooth sailing. However, I ran into a small(though important) issue and decided that it might be fun to write a tiny blog post about the 5 minute fix. The screenshot below illustrates the issue:

Peon without Z sorting

As you can see, the peon is being rendered on top of the tree, even though according to his position in the game world, he would technically be "behind" the tree. I say "behind" because this world isn't exactly 3D. Since the game is rendered completely in 2D, I have to do a little bit of black magic in order to make sure everything renders in the correct order; this technique is commonly called Z-Sorting.

Except, it's actually not black magic at all. It's super simple. All you need are the hit boxes of the sprites in your world.
Hit boxes

Once you have the hit box values, we need to do a simple sort. If the bottom edge of Sprite A is lower than the bottom edge of Sprite B, then the draw priority for that sprite will be higher. Here is what it looks like in C++, using a list::sort and a lambda expression:

m_entities.sort([](Entity* a, Entity* b)
{
    Rectangle aHit = a->GetHitBox();
    Rectangle bHit = b->GetHitBox();

    return (aHit.y + aHit.height) < (bHit.y + bHit.height);
});

Super simple. In terms of efficiency, if you have some sort of culling in your world, it should be fine. It's just a basic compare. In this example though, I am just looping through all the entities in the entire game, which is sure to cause me some performance issues down the line.

Below is a screenshot of the game with the Z sorting in place:
Peon with Z sorting

Look at that sneaky peon hiding behind that tree...