How can I call an instance methode after an input event?

Hello !
so player is a instance of Player object, and run() is one of its method. I can’t find a way to call the player.run() method when I press the W key on my keyboard
Player.js:

export default class Player extends Character  
constructor(scene, param) {
    super(scene, param)
    this.speed = param.speed

}
run() {
    this.speed = this.speed * 1.5
}

}

This is what I wrote in create() :

this.player = new Player()
this.keyW  = this.input.keyboard.addKey('W')
this.keyW.on('down', this.player.run )

I have tried multiple other way but I didn’t find a way to give the function the instance’s context ( I always get something like “‘this’ is undefined” or “player is undefined”

I tried to look for example and doc but didn’t find a solution.
Do you have any idea what am I doing wrong ?

There is an optional third parameter to “on” which is the context (aka what “this” refers to on function call):

this.keyW.on('down', this.player.run, this.player);

I hope that solves your problem.

1 Like