The score is not visible

I do not know why when obtaining points, the numbers are overwritten on top of each other

//-------------------- Score -------------------------------------//
function Impact(){score++}
this.add.text(16, 16, 'SCORE '+ score,{ fontSize:'32px', fill:'#fff',fontFamily:'verdana, arial, sans-serif'});
//----------------------------- Create coin -------------------------//
this.coin = this.physics.add.image(Phaser.Math.Between(0,800), 100, 'coin').setDisplaySize(40, 40)
    
this.physics.add.collider(this.coin, player, getCoins, null, this);
    
function getCoins(){ score += 5;
this.coin.body.setCollideWorldBounds(true);
this.sound.add('soundCoin').play(); this.coin.setVelocityY(-1)
this.coin.setPosition(Phaser.Math.Between(0,800), Phaser.Math.Between(0,600), 'coin')}}}

I haven’t used Phaser in a while but I believe your issue is that you are creating the score text every time.

You need to assign the score text to a variable and set the text.

Something like:

const scoreText = this.add.text(16, 16, ‘SCORE ‘+ score,{ fontSize:‘32px’, fill:’#fff’,fontFamily:‘verdana, arial, sans-serif’});

// Only run this when you want to update the score
scoreText.setText(“new score”);

1 Like

I think Phailser (great name, btw) has the right idea. As a good rule of thumb, be careful with anything with a “.add” in it, especially as a response to an input or stemming from the update function. A lot of things in Phaser are created and added to a scene and are then reusable.

For example, it might not make a noticeable difference in performance, but you could create your coin just once in your scene’s create function, then whenever it’s collected use disableBody(true, true) to make it “disappear” without actually removing it from memory or from the scene, then use enableBody(true, x, y, true, true) to “recycle” it back into your scene as the next coin. If you want to delve a little deeper into it, check out tutorials or examples for “object pools” in Phaser. It looks like you may already be doing something like this, I don’t know what the rest of your code looks like.

You might want to double-check your use of this.sound.add as well. That’s another object you could store in a variable on your scene and then replay whenever you need it:

// In Scene
create() {
  this.coinSound = this.sound.add('soundCoin');
}
// In response to collecting the coin, probably as a collider callback
function getCoins() {
  this.coinSound.play();
}
1 Like