The easiest way to check a variable multiple time is as James mentiond in the game loop, the update function.
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
scene: {
create,
update
},
// ...
};
function create () {
// ...
}
function update () {
//... this function is called 60 times per second
}
new Phaser.Game(config);
You just will have to becareful how to access the variables. Make the part of the object like this this.score = 2 or make the global variable. I would not recommend the later.
Update, based on comment:
document.body.style = 'margin:0;';
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
physics: {
default: 'arcade',
arcade: { gravity: { y: 100 }},
},
scene: {
create,
},
};
function create () {
let score = 0;
let label = this.add.text(10,10, 'Score: 0')
.setScale(1.5)
.setOrigin(0)
.setStyle({fontStyle: 'bold', fontFamily: 'Arial'});
let player = this.add.rectangle( 50, 10, 10, 10, 0xffffff );
// adding a physics body to the GameObjects
this.physics.add.existing(player);
// create "Coins" GameObjects
let coin1 = this.add.rectangle( 50, 50, 10, 10, 0xff0000 );
let coin2 = this.add.rectangle( 50, 80, 10, 10, 0xff0000 );
// adding a physics body to the GameObjects
this.physics.add.existing(coin1, true);
this.physics.add.existing(coin2, true);
// collider: callback function that checks if the player collides with coins
// One could also use the function "overlap", if the player should not be slowed down, on collision
this.physics.add.collider(player, [coin1, coin2], (p,c) =>{
// remove coin
c.destroy();
// add score
score += 2;
// update label
label.setText(`Score: ${score}`);
});
}
new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>