phaser-framework

Is it possible to run a function inside Phaser 3, this.input.on dragstart?


I am writing a game of Solitaire in Phaser 3 and want to run a function inside of this.input.on('dragstart', .... I can drag a single card inside of dragstart, but I need a function to work out which other cards to drag? I have declared the function like so:

getOtherCards(card)
{
    ...
}

I try to use getOtherCards inside of my dragstart, like so:

this.input.on('dragstart', function (pointer, card) {
    // Find all cards in this stack that should move together
    this.getOtherCards(card);
});

In my console I get an error saying getOtherCards has not been declared? My question is can I run a function like this inside of my dragstart, and if not, what is my alternative?


Solution

  • You have to pass the scope to the event function, just set the second argument to this (= the current scene):

    this.input.on('dragstart', function (pointer, card) {
        // Find all cards in this stack that should move together
        this.getOtherCards(card);
    }, this); // <-- Scope
    

    Here is the link to the documentation.

    An Alternative, can be to use an arrow function, than you will not need to pass the scope:

    this.input.on('dragstart', (pointer, card) => {
        // Find all cards in this stack that should move together
        this.getOtherCards(card);
    });