Sorting children of any container by y
property (you can also add sorting by x
, just modify ["y"]
-> ["y", "x"]
, so it will be suitable for isometric objects as well in case they all have the same size, 1x1 tile for instance):
public static function sortChildren(container:DisplayObjectContainer):void
{
const children:Array = [];
const len:uint = container.numChildren;
const sortOnProps:Array = ["y"];
var i:uint;
for(i=0; i < len; i++)
children.push(container.getChildAt(i));
children.sortOn(sortOnProps, Array.NUMERIC);
var child:DisplayObject;
i = 0;
while (i < len)
{
child = DisplayObject(children[i]);
container.setChildIndex(child, i);
i++;
}
}
Test:
var container:Sprite = addChild(new Sprite()) as Sprite;
var sh:Shape;
for(var i:int =0; i < 100; i++)
{
sh = new Shape();
sh.graphics.beginFill(0xFFFFFF*Math.random(), 1);
sh.graphics.drawCircle(50, 50, 50);
sh.graphics.endFill();
container.addChild(sh);
sh.x = int(Math.random() * 500);
sh.y = int(Math.random() * 500);
}
sortChildren(container);
Result: