如何结束 Phaser 中的状态以及导航回之前的状态

How to end a state in Phaser as well as navigate back to a previous state

我是 Phaser 的新手,我一直在编写一个多层次益智游戏。

状态的层次结构如下所示 - 菜单 -> 级别 1 -> 级别 2 -> 等等

现在假设我正在玩关卡 1,在关卡完成后或在中间按返回键时,我希望能够返回到菜单状态,然后从那里我希望能够导航回如果我想继续玩,请提高水平。

最初我假设 this.state.start( 'anyLevel') 可以带我到任何状态,并且该状态通常会 运行 就像 运行 自启动以来第一次。但事实证明,回到已经被解雇过一次的州是很困难的。我需要的是能够返回到以前的状态,并且该状态应该像 运行 自启动后第一次运行时那样。 我在某处读到我需要在开始新状态之前通过 shutDown() 清理状态,我做了:

  shutdown: function() {
    this.game.world.removeAll();
   }

在开始每个新级别之前,但它仍然没有帮助。我也试过使用:

this.state.start( 'anyLevel', true, false);

但事实证明没有用。调试器不显示错误,这意味着程序在语法上是正确的,但我没有正确掌握该机制。

提前致谢。

首先,在制作基于关卡的游戏时,我不建议将每个关卡都置于单独的状态,请参阅相关回答here and here

除此之外,我一直都像你发布的那样使用 state.start(),它工作正常,所以像这样:

// from level select state, switch to game state..
this.game.state.start('MyGameState');

// ..and from game state, switch back to level select state
this.game.state.start('MySelectState');

那么您遇到了什么错误或意外行为?也许您的问题是因为您在该状态下使用的对象变量不是该状态的"connected"?我的意思是,精灵和敌人等变量是在状态之外创建的,还是像下面的代码那样是状态的一部分?

GameState = function(game) {
    // reference to main game object
    this.game = game;

    // object variables are part of this state
    this.myplayer;
    this.myenemies;
    //..etc.
};

GameState.prototype = {

    create: function() {
        this.myplayer = this.game.add.sprite(100, 100, 'mysprites', 'smileydude');
        this.myenemies = this.game.add.group();
        //..etc.
    },
    update: function() {
    },
    //..
    doResetCurrentLevel: function() {
        this.state.start('MyGameState', true, false);
    }
};

顺便说一句,请注意如何通过启动它来简单地重置当前状态。启动状态会再次触发 create() 函数来清理和刷新精灵和敌人变量。我不完全确定这是如何工作的,但我一直认为 JavaScript 垃圾收集器会处理这个问题。