Reputation: 23
I made a variable that displays a number through game.add.text(...)
in the create function but i want the text to update every time i press a button, since the variable changes. And if i do game.add.text(...)
in the update function it gets stacked and many many layers of text appear.
Upvotes: 2
Views: 2665
Reputation: 8571
Here's a simple version that should give you an idea of how to handle this.
<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>
So, instead of creating a new text object, store a reference to the one you create and use setText()
to update it.
Upvotes: 3
Reputation: 3
try this:
clickBtn:number = 0; // for example
game.add.text('Clicks ' + this.clickBtn);
this.btn = this.add.button(some code, this.yourFunction);
this.yourFunction() {
this.clickBtn += 1;
}
I think it would help you.
Regards, Sergey.
Upvotes: 0