Sprite undefined in Player Class

Hi guys !

This is my first message inside this forum.
I have a problem to reference my sprite inside Player class.
“Cannot read property ‘setVelocityX’ of undefined”
This is my code :

class Player{
				constructor(scene){
					this.spr = scene.physics.add.sprite(64, 64, 'player');
					this.spr.x = 64;
					this.spr.y = 64;
					this.ok = true;
					this.velocLeft = 0;
					this.velocRight = 0;
					this.velocUp = 0;
					this.velocDown = 0;
					this.left = scene.input.keyboard.addKey('Q');
					this.up = scene.input.keyboard.addKey('Z');
					this.right = scene.input.keyboard.addKey('D');
					this.down = scene.input.keyboard.addKey('S');
				}

				move(){
					this.left.on('down', function(){
						if(this.spr.x > 0){
							this.velocLeft = -250;
							this.spr.setVelocityX(this.velocLeft);
						}
					});

					this.left.on('up', function(){
						this.velocLeft = 0;
						this.spr.setVelocityX(this.velocLeft);
					});

					this.up.on('down', function(){
						this.velocUp = -250;
						this.spr.setVelocityY(this.velocUp);
					});

					this.up.on('up', function(){
						this.velocUp = 0;
						this.spr.setVelocityY(this.velocUp);
					});

					this.right.on('down', function(){
						this.velocRight = 250;
						this.spr.setVelocityX(this.velocRight);
					});

					this.right.on('up', function(){
						this.velocRight = 0;
						this.spr.setVelocityX(this.velocRight);
					});

					this.down.on('down', function(){
						this.velocDown = 250;
						this.spr.setVelocityY(this.velocDown);
					});

					this.down.on('up', function(){
						this.velocDown = 0;
						this.spr.setVelocityY(this.velocDown);
					});
				}


			}

:wave:

It can be solved by adding this as the third argument to on().

But I don’t think you should call on() from move(). It adds a new event handler each time. Instead do

if (this.left.isDown) {/*…*/}