Flash & AS3 info, source, & experiments
AS3 DisplayObject Auto Depth Sorter
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.
Example:
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.
Usage:
var mcContainer:SpriteAutoSorter = new SpriteAutoSorter(); mcContainer.sPropertyToSortOn = "y"; // "y" is actually used by default so this line is not necessary mcContainer.beginSorting();
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!
| Print article | This entry was posted by Nate Chatellier on November 29, 2011 at 11:02 pm, and is filed under ActionScript, Flash, Tools & Utils. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 5 months ago
So if you have 100 items on screen, you will do 100 x setChildIndex() each ENTER FRAME, even if nothing has changed. This is not optimized !
about 5 months ago
@Anthony:
I programmed for the worst-case scenario: a fast-paced action game where all of the objects are moving nearly every frame and there is a high probability of multiple necessary depth swaps. This is when the hit on the cpu is likely the most intense in-general and so this method of depth-sorting becomes very efficient since it doesn’t do any additional checks or conditions that might slow it down if every single object passed the conditional checks and needed to be sorted.
The best-case scenario would occur when objects aren’t moving much or at all. “Optimizing” this as you suggest would most definitely help performance in the best-case scenario, but would hurt performance in the worst-case scenario. In all of the games that I have made, the best-case scenario has always been when there was the lightest load on the cpu. So if I have to choose whether the code will perform better in the best-case scenario or better in the worst-case scenario, I choose better performance in the worst-case scenario.
If it’s not common for objects to swap frequently in your game, you could easily add a flag to each game object that changes to true if the object has moved since the last frame. Or handle it a number of other ways too.
Since, it just so happens that all of the games I’ve created so far fit into the worst-case scenario I described above, that’s why I wrote it the way I did. Hope that helps. Thanks for the feedback.