Creating scores using phaser.js

Hi I am trying to upgrade the Bug Dodger project. My intentions are:
Create two score variables lastScore(the score you got on that try) and:
highScore(The best score) and I want to display them in dodger.html.
But when I use this code(from my phaser.js file):


//Kill player and set the scores
this.physics.add.collider(gameState.player, bugs, () => {

//game over

//game over text
this.add.text(x, y, ‘Game Over’, {fill: ‘colour’, size: ‘15px’});
this.add.text(x, y, ‘Click to Restart’, {fill: ‘colour’, size: ‘15px’});

//Set the scores
let highScore = 0;

if(gameState.score > highScore) {
highScore = gameState.score;

else {
highScore = highScore;

//print text
document.getElementById(‘highscore’).innerHTML = highScore;
document.getElementById('prevscore).innerHTML = gameState.score;


It displays the the numbers for prevscore perfectly fine but changes the highScore variable to a smaller score AS WELL as prev score any ideas?
I would appreciate any answers and help, Thanks! :slightly_smiling_face:

To preserve code formatting in forum posts, see: [How to] Format code in posts
Also, you haven’t posted the whole code, so some issues may escape notice.

But based on the code you have posted, your use of gameState.score suggests that score is a property of the gameState object, whereas highScore is not a property of gameState. I think that needs to be fixed. highScore should also be a property of gameState.

In your code, you are initializing let highScore = 0;. Then, if gameState.score > highScore, you are replacing 0 with gameState.score. Furthermore, highScore = highScore; doesn’t seem to do anything meaninful.

As I said, you should have highScore as a property of gameState as well, so that you can access its value through gameState.highScore. This property should be initialized to 0 before the very first round. Afterwards, it should not be reset to 0.

It also appears that your if-else condition blocks aren’t within the body of this.physics.add.collider(gameState.player, bugs, () => { ... });

I would imagine you would want the if condition if (gameState.score > gameState.highScore) { to be within the collider’s callback function. If the condition is true, you would want to make the relevant assignments. If the condition is false, then gameState.highScore should remain unchanged. So most likely, you won’t need the else block because the best high score is already present in the gameState object.

1 Like

Thanks for your help! I was really struggling. Have a GREAT day! :smiley: :smiley:

1 Like