1

我正在开发 Flash Actionscript 3.0 中的横向卷轴游戏。现在我正试图让玩家通过触摸某个对象来进入下一个级别。在加载下一个关卡之前,我尝试从舞台上移除所有上一个关卡的资产(背景和“地板”),即电影剪辑。当下一个关卡加载时,我仍然可以看到上一个关卡的资产,尽管 Player 无法与它们交互。

我环顾互联网并尝试了一些方法来解决我的问题,但我无处可去。以下是我用来从一个级别转换到下一个级别的代码。“bgContainer”仅包含未加载关卡的背景影片剪辑,“allContainer”包含未加载关卡的地板和其他环境对象。这些容器稍后会装载下一层所需的对象。

// Check if the Player has touched Level 1's end point
    private function checkLevel1To2Collision(event:Event):void {
        // Has the Player touched Level 1's end point?
        if (HitTest.intersects(player, level1To2, this)) {

                // Remove Level 1's Background from the stage
                //stage.removeChild(bgContainer);

                removeEventListener(Event.ENTER_FRAME, scrollScreen);

                // Clear everything from the stage (only if there is already something on the stage)
                //while (numChildren > 0) {

                    //for (var stgIndex = 0; stgIndex < stage.numChildren; stgIndex++) {
                        //stage.removeChildAt(0);
                    //}
                //}
                //}

                stage.removeChild(allContainer);
                stage.removeChild(bgContainer);

                // Clear out all elements from the 'allContainer' before reloading the current level
                for (var allIndex1:int = 0; allIndex1 < allContainer.numChildren; allIndex1++) {
                    allContainer.removeChildAt(allIndex1);
                    //if (stage.getChildAt(allIndex1)) {
                        //stage.removeChildAt(allIndex1);
                    //}
                }

                // Remove the elements within 'bgContainer' from the stage
                for (var bgIndex1:int = 0; bgIndex1 < bgContainer.numChildren; bgIndex1++) {
                    bgContainer.removeChildAt(bgIndex1);
                    //if (stage.getChildAt(bgIndex1)) {
                        //stage.removeChildAt(bgIndex1);
                    //}
                }


                // Load Level 2
                loadLevel2(event);
        }
    } // End of 'checkLevel1To2Collision' function  

可以看出,我已经尝试了至少两种技术来卸载上一个级别的资产。我尝试过使用“for”循环逐个删除所有元素。我已经尝试在舞台上有一个对象时删除索引 0 处的舞台元素。在使用“addChildAt()”添加对象时,我还尝试使用“root”而不是“stage”。这些技术都不起作用。我仍然不知道为什么上一个级别不会被卸载。

任何帮助,将不胜感激!

谢谢!

4

1 回答 1

1

如果您不确定 allContainer 的父级是什么,请使用

allContainer.parent && allContainer.parent.removeChild(allContainer.parent);

(这个左侧只是作为一个守卫,以确保仅当 allContainer 在舞台上时才调用右侧,您也可以将其写为:)

if (allContainer.parent)
{
    allContainer.parent.removeChild(allContainer.parent);
}

你写的for循环也有问题,因为在你删除了0处的第一个孩子之后,孩子们都向下移动一个索引,所以1处的孩子现在在0但你的索引已经移动到1,所以你保持失踪的孩子!而是使用这个:

while (allContainer.numChildren)
{
    allContainer.removeChildAt(0);
}

这样,while 循环将继续循环,直到 allContainer 的所有子项都被删除。

或者,如果您希望它以最佳方式快速运行,请使用

var i:int = allContainer.numChildren;
while (i--)
{
    allContainer.removeChildAt(0);
}

希望这可以帮助。

于 2011-10-14T11:33:11.837 回答