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