Jump to content

Single Event for Mouse Click Issue


megamaster
 Share

Recommended Posts

Hi fellow phasers,

I am having difficulty making a single event occur when pointer input is pressed down. I've searched the forums for a solution but nothing seems to be working for me.

The recommendation that I have seen is this code:

game.input.onDown.add(doSomething, this);

function doSomething() {

// will only ever be called once, when the the input is down

}

I simply want to reduce health of a character when the sprite is clicked. This is what I have written:

var player1;
var health1 = 100;

function create() {    
    player1 = game.add.sprite(44, 70, 'stand');
    health1Text = game.add.text(2, 10, 'health: 100', { fontSize: '10px Arial', fill: '#fff' });
    player1.inputEnabled = true;
    player1.onDown.add(update, this);
    

function update() {
    health1 += -10;
    health1Text.text = 'health: ' + health1;

What happens when I run it is that the health constantly decreases without any input pressed. I have tried different input methods as well, but they won't reduce the health by a factor of 10 at a time.

Also the font size is not working for me either.

 

Thanks for any and all help!

Link to comment
Share on other sites

var player1;
var health1 = 100;
var health1Text = undefined;

function create() {    
    player1 = game.add.sprite(44, 70, 'stand');
    health1Text = game.add.text(2, 10, 'health: 100', { font: '10px Arial', fill: '#fff' });
    player1.inputEnabled = true;
    player1.onDown.add(decreaseHealth, this);
}
    
function update() {
    // update things…
}

function decreaseHealth() {
    health1 += -10;
    health1Text.text = 'health: ' + health1;
}
  • fontSize should be font
  • update is probably your state update function; you need a separate callback for the input event
  • you need to declare health1Text in the outer scope if you want to use it in multiple functions
  • check your browser console for error messages
Link to comment
Share on other sites

So here's the error I got using google's console:

Uncaught TypeError: Cannot read property 'add' of undefined
    at Object.create (part2.html:41)
    at c.StateManager.loadComplete (phaser.min.js:8)
    at c.SignalBinding.execute (phaser.min.js:8)
    at c.Signal.dispatch (phaser.min.js:8)
    at c.Loader.nextFile (phaser.min.js:17)
    at c.Loader.fileComplete (phaser.min.js:17)
    at HTMLImageElement.a.data.onload (phaser.min.js:17)

any suggestions?
 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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