在 Phaser3 中切换场景

Switching between scenes in Phaser3

所以我的 Phaser3package.json 中的版本是 3.21.0)应用程序中有两个场景,我会喜欢在没有任何副作用的情况下切换。第一个场景是处理高分菜单,第二个是游戏本身。

相关代码

app.ts 文件如下所示:

const config = {
    title: '<game-name>',
    width: 800,
    height: 600,
    parent: 'game',
    scene: [MenuScene, GameScene],
};

export class GameName extends Phaser.Game {
    constructor(config: any) {
        super(config);
    }
}

window.onload = () => new GameName(config);

MenuScene.ts - 删除了不适用的部分:

class MenuScene extends Phaser.Scene {
    constructor() { super({key: 'MenuScene'}); }

    create():void {
       console.log('create menuscreen');
       const enter = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER);
       enter.on('down', () => { this.scene.start('GameScene'); }
    }
}

GameScene.ts - 也删除了不相关的代码片段:

class GameScene extends Phaser.Scene {
    constructor() { super({key: 'GameScene'}); }

    create = ():void => {
       console.log('create gamescreen');
       const esc = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ESC);
       esc.on('down', () => { this.scene.start('MenuScene'); }
    }
}

问题和我的问题

所以一旦我重复按 EnterEsc 只是为了切换提供的解决方案,它似乎并没有清理背景中的场景。在 console 上,我在切换几次后看到以下内容(在下面的示例中为 6 次):

我已经尝试在 this.scene.start('<scene-key>') 之前调用 this.scene.stop(),但仍然是同样的问题。我已经在阅读 问题,但它似乎没有回答我的问题。有人告诉 start() 应该清理或关闭未使用的。

那么应该如何正确切换场景或者清理当前不用的场景呢?

谢谢!

我就是这样做的

1.- 游戏暂停场景

场景scene_pause将结束game_scene因为最后一个场景将是最上面的场景

isPaused = this.scene.isPaused('scene_game');
if (false === isPaused) {
    this.scene.pause('scene_game');
}
const isNull = this.scene.get('scene_pause');
if (null === isNull) {
    this.scene.add('pause_scene', PauseScene, true);
}

然后当你继续游戏时

isActive = this.scene.isActive('scene_pause');
if (true === isActive) {
    this.scene.remove('scene_pause');
}
isPaused = this.scene.isPaused('scene_game');
if (true === isPaused) {
    this.scene.resume('scene_game');
}

2.- 切换场景游戏结束

this.scene.stop('scene_game'); // stop executing the Update 1rst
... // save the state and score
this.scene.remove('scene_game'); // I remove the scene, because I will add again when start the game
this.scene.stop('scene_ui');
this.scene.switch('scene_game_over');