Jump to content

[object Object] problem with score


issey
 Share

Recommended Posts

Hi there!

I'm having a little issue with updating my game's score correctly. I set the score to += 10 on each click, but it gets stuck at 10.

I also have my score displaying " score: [object Object]10 " instead of "score: 10". It probably has to do with how I added the score to the collectStar function?

Here's my code:

var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {
  
  game.load.image('star', 'assets/images/star.png');
}

function create() {

  //Score 
  var score = 0;
  localStorage.setItem("save", JSON.stringify(score));
  console.log('Score: '+ localStorage.getItem("save"))

  var scoretext;
  scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '24px', fill: '#222' });

  //Star Group
  starGroup = game.add.group();
  for (var i = 0; i < 3; i++)
  {starGroup.create(game.world.randomX, game.world.randomY, 'star');}
  
  starGroup.setAll('inputEnabled', true);
  starGroup.setAll('input.useHandCursor', true);

  // Animate and destroy on star click
  starGroup.callAll('events.onInputDown.add', 'events.onInputDown', collectStar);
}

function collectStar (star, score) {
  
  // Add a timer before destroying star
  game.time.events.add(1000, star.destroy, star);
  
  // Add and update the score
  score += 10;
  scoreText.text = 'score: ' + score;
  
  localStorage.setItem("save", JSON.stringify(score));
  console.log(localStorage.getItem("save"))
  
}

function update() {}

 

Link to comment
Share on other sites

Hi !

The problem is your score variable is not a global.

The score variable in "create" function is different from the score variable in the "collectStar" function.

I don't think (Actually, I am sure it is not the case) the actual score will be passed to collectStar function.

Just do:

function collectStar (star) {

And make your score variable global by declaring it outside the functions (after game declaration for example)

var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, '', { preload: preload, create: create, update: update });
var score = 0; 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...