Vatsa Pandey
Vatsa Pandey

Reputation: 607

PhaserJs/javascript: My array is updating too many times

So I have some code making a simple inventory, like this:

else if (this.inventory.indexOf(tileType) != -1) {
              this.inventory[this.inventory.indexOf(tileType) + 1] =
                this.inventory[this.inventory.indexOf(tileType) + 1] - 1;
              console.log(this.inventory);
              return;

In phasers update function, i'm using this.input.manager.activePointer.isDown as my event trigger, and it subtracts it for as long as the mouse is down, which results in at least 6 updates cycles for the quickest clicks

I've tried methods like return; etc. , but it always goes subtracting multiple times. So is there any javascript method i could use, or a better phaser input event?

Upvotes: 1

Views: 86

Answers (1)

winner_joiner
winner_joiner

Reputation: 14880

As @Geshode mentioned in the comments, I would also setup the mouse event in the create function, and remove the other mouse code from the update function. (checkout the documentation for details)

Since this event will be executed only once per click/touch.

function create(){
    ...
    this.input.on('pointerdown', () => {
        if (this.inventory.indexOf(tileType) != -1) {
            this.inventory[this.inventory.indexOf(tileType) + 1] = 
                this.inventory[this.inventory.indexOf(tileType) + 1] - 1;
            console.log(this.inventory);
            ...
         }
    });
}

Check out these official Mouse examples

Update example:

The idea is to make all local variables needed in the event function, that are created / used in the update function with "scene properties".

Out of tileType you would have to make this.tileType, and so on. (you just have to beware of naming collisions)

How it could look like:

function create(){
    ...
    this.input.on('pointerdown', () => {
        // the tileType is now a property of the current scene
        if (this.inventory.indexOf(this.tileType) != -1) {
            this.inventory[this.inventory.indexOf(this.tileType) + 1] = 
                this.inventory[this.inventory.indexOf(this.tileType) + 1] - 1;
            console.log(this.inventory);
            ...
         }
    });
}

Or better use a "gameState" object. In the create function add this.gameState = {}; and than each variable you would like to add / access, just write this.gameState.tileType = 1;. So long the context (this) is the scene, this should work, and there will be no naming problem.

Upvotes: 1

Related Questions