0

我正在用 Flash CS5/AS 3.0 编写一个游戏,它试图通过根据 Y 位置以升序绘制所有相关电影剪辑来模拟景深,即舞台上较低的东西与舞台上较高的东西重叠。因此,与 Y 位置为 20 的 MovieClip 相比,Y 位置为 10 的 MovieClip 需要具有较低的索引,因此第二个将绘制在第一个之上。

我写了一个快速而肮脏的函数来测试它。在跟踪过程中,我注意到当我靠近舞台顶部时,卡车的索引为 0,但如果我走得太远,它会完全从舞台上消失。然后跟踪开始生成此错误:

ArgumentError:错误 #2025:提供的 DisplayObject 必须是调用者的子对象。
        在 flash.display::DisplayObjectContainer/getChildIndex()
        在 EICT::Game/ReorganizeDisplayIndexes()
        在 EICT::Game/loop()

theTruck 是玩家控制的车辆 Enemies、Cones、Rocks 的 MovieClip 都是包含 MovieClips 的数组

他们都没有事件监听器。

    private function ReorganizeDisplayIndexes(): void
    {
        var drawableObjects:Array = new Array();
        drawableObjects.push(theTruck);
        drawableObjects = drawableObjects.concat(Enemies, Rocks, Bushes);
        drawableObjects.sortOn("y", Array.DESCENDING | Array.NUMERIC);
        drawableObjects.reverse();
        trace(collisionLayer.getChildIndex(theTruck));
        for (var a:int = collisionLayer.numChildren - 1; a >= 0; a--)
        {
            collisionLayer.removeChildAt(a);
        }
        for (var i:int = 0; i < drawableObjects.length; i++)
        {
            collisionLayer.addChild(drawableObjects[i]);
        }
    }
4

2 回答 2

1

提示:您不需要先移除孩子。当您addChild()在对象上使用时,它会自动重新添加到下一个最高深度。

也就是说,您只需要执行以下操作:

drawableObjects.sortOn("y");

for each(var i:DisplayObject in drawableObjects)
{
    if(i.parent)
        i.parent.addChild(i);
}
于 2012-03-01T07:03:22.457 回答
0

使用 setChildIndex 而不是删除和重新添加:

for (var a:int = collisionLayer.numChildren - 1; i >= 0; i--)
{
    collisionLayer.setChildIndex(drawableObjects[i], i);
}

此外,先按降序排序然后反转数组有点浪费。从升序开始!

于 2012-03-01T09:15:00.273 回答