As3:如何制作Y位置最高的动画片段出现在前面?

时间:2014-02-19 11:31:55

标签: actionscript-3 layer

如何让舞台上的动画片段(以编程方式添加)出现在前面和另一个上面?

我希望Y值最高的人能够在Y值较低的人面前。

谢谢!

        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();
            }
        }

1 个答案:

答案 0 :(得分:2)

y属性对任何容器的子项进行排序(您还可以按x添加排序,只需修改["y"] - &gt; ["y", "x"],这样就适合等距对象以及它们都具有相同的大小,例如1x1平铺):

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++;
    }
}

测试:

    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);

结果:

enter image description here