无法更改 Phaser 3 中的场景

Unable to change scenes in Phaser 3

我的 Phaser 3 游戏有一个名为 game 的场景,我从中调用另一个场景 mainMenu 使用 check() 加载场景中使用的方法:

//inside check() 
this.scene.start("mainMenu");

但这会导致错误:

未捕获类型错误:无法读取未定义的 属性'start'

我相信它与代码中的 this 有关,但我不确定。那么我如何从一个函数开始一个场景。

Load.js

var config{
//game config goes here
scenes: [mainMenu,game]
}

var game = new Phaser.Game(config);
function check(){
if(game over == true){
this.scene.start("mainMenu");}
}

game.js

class game extends Phaser.Scene {
constructor() {
super({ key: "game" });
}
create() {
 check();
}
}

在检查函数的主体中 "this" 指的是检查函数本身,它上面没有场景 属性,这就是你看到错误的原因。

如果您使用 "call" 方法调用检查并通过游戏的 "this" 它应该可以解决您的问题,但这可能不是最干净的方法。

另外创建我相信只在初始化时调用,所以我不认为此时游戏结束会是真的(你可能想在更新中调用它)

class game extends Phaser.Scene {
  constructor() {
    super({ key: "game" });
  }
  create() {
    check.call(this);
  }
}

编辑:以下可能是我处理问题的方法:

class MainScene extends Phaser.Scene {
  constructor() {
    super({ key: "MainScene" });
  }

  create() {}

  isGameOver() {
    // logic to determine if the game is over
  }

  update() {
    if (this.isGameOver()) {
      this.scene.start("MainMenu");
    }
  }
}

var config {
  //game config goes here
  scenes: [
    MainMenu,
    MainScene
  ]
}

var game = new Phaser.Game(config);