0

我有一个暂停游戏的代码,它运行暂停功能,如下所示:

public function onKeyPress(keyboardEvent:KeyboardEvent) :void
{
    //Check for pause
    if(keyboardEvent.keyCode == Keyboard.P)
    {
        //If the timer is still running
        if(gameTimer.running)
        {
            gameTimer.stop();
            Mouse.show();
            pauseText = new PauseText();
            pauseText.x = 150;
            pauseText.y = 100;
            addChild(pauseText);
            //If the player is using the mouse, resume by clicking on the player
            if(mouseControl)
            {
                player.addEventListener(MouseEvent.CLICK, resumeGame);
                pauseText.pauseInformation.text = "click on yourself";
            }
            else
            {
                pauseText.pauseInformation.text = "press 'p'";
            }
        }
        else
        {
            //Only allow the player to resume with P IF he is using the keyboard
            //This prevents cheating with the mouse.
            if(!mouseControl)
            {
                gameTimer.start();
                removeChild(pauseText);
                pauseText = null;
            }
        }
    }
}

游戏运行完美。在我第一次播放时,暂停功能起作用。但是,如果稍后我死了并重新启动游戏,然后暂停它,我会收到以下消息:

TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/removeChild()
    at Game/onKeyPress()

游戏仍然运行良好。但是,每次我暂停或取消暂停时,都会出现此错误。如果我再次死机,重新启动,然后暂停,会出现其中两个错误。据我所知,它似乎试图删除 pauseText ......但我在第一次播放时一直很好地删除它,我使用 removeChild() 然后将我的代码的其他部分设置为 null 并且它可以工作美好的。另外,如果我添加一个跟踪(“a”);在函数头之后的语句,我在输出面板上出现“a”之前得到错误。

怎么了?

附加说明:如果我在第一次播放时根本不使用暂停功能,那么在第二次播放时调用它时不会出错。

4

3 回答 3

0

将 removeChild 放入 'if' ,这将解决错误:

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

但无论如何你应该检查问题的根源是什么,也许'gameTimer.running'在开始时是假的?

于 2012-08-27T06:54:53.803 回答
0

您可能会实例化另一个 Game 对象(包含整个游戏的对象),而不会删除前一个游戏的事件侦听器。这可以解释这种行为,因为您有多个 KeyboardEvent.KEY_DOWN 侦听器处于活动状态,并请注意,当您停止游戏时,您很可能会停止其中的计时器,因此您的“if (gameTimer .running)" 语句被执行,但是计时器被有效地停止而没有生成 pauseText。所以,你错过了一个

removeEventListener(KeyboardEvent.KEY_DOWN,onKeyPress);

在您的游戏破坏代码中。

于 2012-08-27T09:56:37.143 回答
0
if (!mouseControl) {
    gameTimer.start();
    if (pauseText && contains(pauseText)) {
        removeChild(pauseText);
        pauseText = null;
    }
}
于 2012-08-27T11:04:08.230 回答