How do I make the movieclips I have on stage (added programatically) appear in front one and another?

I want the ones who have the highest Y value to be in front of those with lower Y value.

Thanks!

        private function buyWorker(event:MouseEvent):void
        {       

        //Random Y pos
            var randomYPos = Math.floor(Math.random() * 400);

        //Check if the player can afford it
            if (moneyAmount >= workerCost)
                {
                    clicksound.play();

                //Deduct the cost
                    moneyAmount -= workerCost;

                var worker:Worker = new Worker();

                //Spawn the worker
                    addChild(worker);

                    for (var i:int =0; i < (root as MovieClip).numChildren; i++)
                    {
                        var child:DisplayObject = (root as MovieClip).getChildAt(i);
                        if(child is Worker) {
                            workerArray.push(child);
                        }
                    }

                //Set the workers position
                    worker.x = -50;
                    worker.y = yRange(140, 520);
                }

            else
            {
                errorsound.play();
            }
        }
有帮助吗?

解决方案

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:

enter image description here

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top