首页 > 解决方案 > Phaser 3 切换场景重叠文本

问题描述

我正在创建一个用户界面。我在主场景和子场景之间传递文本。

我打算做的是重用子场景并根据按下的按钮更改文本。在按下“按钮 1”时,转到子场景并显示“按下按钮 1”。然后在单击文本时返回主场景。在按下“按钮 2”时,转到子场景并显示“按下按钮 2”。然后在单击文本时返回主场景。

但是,在按下两个按钮后,文本会重叠。

在此处输入图像描述

我认为它会创建一个新场景,但看起来它正在向同一个场景添加新文本。我该如何解决这个问题?

场景.js

class MainScene extends Phaser.Scene 
{
    constructor ( )
    {
        super();

        Phaser.Scene.call(this, { key: 'mainscene' });
    }

    create()
    {
        const button1 = this.add.text(100, 100, 'button1', { fill: '#0f0' });

        button1.setInteractive();

        button1.on('pointerdown', this.button1Pressed, this); 

        const button2 = this.add.text(100, 200, 'button2', { fill: '#0f0' });

        button2.setInteractive();

        button2.on('pointerdown', this.button2Pressed, this); 
    }

    button1Pressed () 
    {
        this.scene.start('subscene', { text_to_print: "button ONE pressed"});
    }

    button2Pressed () 
    {
        this.scene.start('subscene', { text_to_print: "button TWO pressed" });
    }
}

class SubScene extends Phaser.Scene 
{
    constructor ( )
    {
        super();

        Phaser.Scene.call(this, { key: 'subscene' });

        this.text_to_print = null;
    }

    init ( data )
    {
        this.text_to_print = data.text_to_print;
    }

    create()
    {
        
        
        var style = { font: "65px Arial", fill: "#777777", align: "center" };
        var text = this.add.text(100, 100, this.text_to_print, style);

        text.setInteractive();

        text.on('pointerdown',this.goBack,this);
    }

    goBack()
    {
        this.scene.switch('mainscene');
    }
}


var config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
        width: 960,
        height: 540
    },
    scene: [MainScene, SubScene ]
};

var game = new Phaser.Game(config);

场景.html

<!DOCTYPE html>
<html>
<body>

    <script src="phaser.min.js"></script>
    <script src="scenes.js"></script>
    
</body>

</html>

标签: phaser-framework

解决方案


sammehttps://phaser.discourse.group/t/scene-switching-text-overlapping-previous-text/9376中回答了这个问题

它应该是

class SubScene extends Phaser.Scene {
    // …
    goBack() {
        this.scene.start('mainscene');
    }
}

此外,场景构造函数应该是,例如,

super({ key: 'mainscene' });
Phaser.Scene.call() can be removed.

推荐阅读