【问题标题】:As3: How to make movieclips with the highest Y position appear in front?As3:如何让Y位置最高的movieclip出现在前面?
【发布时间】:2014-03-19 16:58:43
【问题描述】:

如何让我在舞台上(以编程方式添加)的影片剪辑一个接一个地出现在前面?

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

【问题讨论】:

  • 你能展示一下你是如何在舞台上添加它们的代码吗?因为我们需要在那里添加一些行。

标签: actionscript-3 layer


【解决方案1】:

通过y属性对任何容器的子项进行排序(您也可以通过x添加排序,只需修改["y"] -> ["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);

结果:

【讨论】:

  • sortOn,我最喜欢的数组的秘密特性。我希望他们将其添加到Vector.&lt;T&gt;
猜你喜欢
  • 1970-01-01
  • 2011-03-12
  • 2011-09-24
  • 1970-01-01
  • 2021-04-12
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多