Hi there.
In a dungeon crawler, I have some doors Images I click to open.
I have this code in a class Game extends Phaser.Scene
:
objectsEvents(objectsList) {
// ... Loop over objects to add events on
// Toggle door event
object.setInteractive().on('pointerdown', this.toggleDoorWithButton, {
target: object,
game: this
});
// ... other events
}
toggleDoorWithButton() {
// Open the door/target
// Code is decoupled in order to have other triggers that can toggleDoor() directly
this.game.toggleDoor(this.target);
}
Where object
is an Image GameObject
. The only way I found it to work is to give a context to the listener :
{
target: object,
game: this
}
In toggleDoorWithButton()
I want to get the object clicked and the Game scene in order to open the door in question (because toggleDoor() is a method of Game). In that function this
is by default the object itself, the target, the door, but I lose the link to the Game Scene… that’s why I had to define a more complete object with the listener and add Game to it. It seems redundant at first view.
Is it the right way to do that in JS with Phaser ? In pure JS, we can catch the event and get the currentTarget, what I did not manage to do here (the event is the JS one, not a Phaser one).
Before answering, check the code I also try (that came with Phaser samples) but not in a class :
function objectsEvents(objectsList) {
// ... Loop
// Toggle door event
object.setInteractive().on('pointerdown', toggleDoorWithButton);
}
function toggleDoorWithButton() {
// "this" is the Game Scene
toggleDoor(this.input.gameObject);
}
In this case this
is the Game Scene and the gameObject clicked seems to be stored in this.input.gameObject
and it works fine but this code placed in a class,
this.input.gameObject
is undefined even if this = Game.
Any best practice on this would be appreciated