A common issue I have while creating Flash/ActionScript 3 games is needing to depth sort DisplayObjects based on some property of the display object itself (most often, their y coordinate). I do this so often that, a while back, I created a special class that extends Sprite and automatically handles this for you. I thought it was finally time to share this handy utility class with the world, so here it is.
For an example, check out the Kung Fu Panda Tales of Po game I worked on. When the characters pass by each other across the “y” plane, they are automatically depth sorted without any extra coding work on my part.
var mcContainer:SpriteAutoSorter = new SpriteAutoSorter();
mcContainer.sPropertyToSortOn = "y"; // "y" is actually used by default so this line is not necessary
And that’s it! Now just addChild and removeChild like normal and everything will be handled for you. To save on performance, you should call stopSorting() when it is no longer required. Enjoy!