Z-Sorting
JPMartineau asks, “how do you handle a player partially hidden by raised terrain? What you call half-tile obscuring.” (Also frequently called z-sorting.)
Layered
Z-sorting is actually pretty easy in Flixel. In End of Line, we have three layers. We have objects in the mid-ground that can partially obscure other objects in the mid-ground. We also have objects on the ground, beneath other objects, and in the air, above all other objects.
The three layers are easy, we just use three FlxGroup’s (actually our own subclassed DisplayGroup, see below), that we add to our PlayState in order:
add(lowDisplayGroup);
add(midDisplayGroup);
add(highDisplayGroup);
Then we add our objects to the appropriate layer. Repair pads and the bottom of elemental stations are added to the lowDisplayGroup. EOL, walls, and the other bots are added to the midDisplayGroup. The tops of elemental stations are added to the highDisplayGroup.
When a flyer needs to repair something, we move it to the highDisplayGroup during flight and then back to the midDisplayGroup when it lands.
Sorted
Sorting within the groups is a little trickier (but not much). FlxGroup provides sort() and sortHandler() functions. We create a subclass of FlxGroup called DisplayGroup and override the sortHandler() to sort on the bottom left coordinate of each sprite (the default is top left):
override protected function sortHandler(Obj1:FlxBasic,Obj2:FlxBasic):int
{
var base1:Number = Obj1['y']+Obj1['height'];
var base2:Number = Obj2['y']+Obj2['height'];
var x1:Number = Obj1['x'];
var x2:Number = Obj2['x'];
if(base1 < base2) {
return _sortOrder; // above == behind
}
else if(base1 > base2) {
return -_sortOrder; // below == in front
}
else {
if(x1 > x2) {
return _sortOrder; // right == behind
}
else if(x1 < x2) {
return -_sortOrder; // left == in front
}
else {
return 0;
}
}
}
Then at the end of our PlayState’s update() function we just call:
lowDisplayGroup.sort();
midDisplayGroup.sort();
highDisplayGroup.sort();
Once sorted, Flixel’s drawing code does the rest!

