我如何在 Phaser 中制作和更新文本 (HTML)

How can i make and update a text in Phaser (HTML)

我在创建函数中通过 game.add.text(...) 创建了一个显示数字的变量,但我希望每次按下按钮时文本都更新,因为变量发生了变化。如果我在更新函数中执行 game.add.text(...) 它会堆叠起来并出现许多层文本。

试试这个:

clickBtn:number = 0; // 例如

game.add.text('Clicks ' + this.clickBtn);

this.btn = this.add.button(一些代码,this.yourFunction);

this.yourFunction() {

this.clickBtn += 1;

}

我想这对你有帮助。

此致,谢尔盖。

这是一个简单的版本,可以让您了解如何处理这个问题。

<script>
    var game = new Phaser.Game(400, 300, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });
    // You'll need to make sure your button click action can access the number to display.
    var clickCount = 0;
    // We'll also need to keep track of the text object that we add to the game.
    var clickCounter;

    function preload() {
        game.load.image('button', 'assets/button.png');
    }

    function create() {
        game.stage.backgroundColor = '#124184';
        // When creating the text object, make sure it'll be accessible from our button handler.
        clickCounter = game.add.text(5, 5, 'Total clicks: ' + clickCount, { fill: '#ffffff', font: '14pt Arial' });

        game.add.button(200, 150, 'button', actionOnClick, this);
    }

    function actionOnClick() {
        clickCount++;
        // The key here is setText(), which allows you to update the text of a text object.
        clickCounter.setText('Total clicks: ' + clickCount);
    }
</script>

因此,不要创建新的文本对象,而是存储对您创建的对象的引用并使用 setText() 更新它。