0

I'm coding a project and I've got a problem when I try getting keyboard input in a dedicated class.

So this is my Controller class :

Controller = function() {
// Initialisation clavier 
document.onkeydown = this.onKeyDown;
document.onkeyup = this.onKeyUp;
// Touches 
this.left = false;
this.up = false;
this.down = false;
this.right = false;
}

// Touche appuyée 
Controller.prototype.onKeyDown = function(event) {
    if (event.keyCode == 37) {
        this.left = true;
    }
    else if (event.keyCode == 38) {
        this.up = true;
    }
    else if (event.keyCode == 39) {
        this.down = true;
    }
    else if (event.keyCode == 40) {
        this.right = true;
    }
}

// Touche relâchée 
Controller.prototype.onKeyUp = function(event) {
    if (event.keyCode == 37) {
        this.left = false;
    }
    else if (event.keyCode == 38) {
        this.up = false;
    }
    else if (event.keyCode == 39) {
        this.down = false;
    }
    else if (event.keyCode == 40) {
        this.right = false;
    }
}

... with which I create an occurence during initialization. But when I try to get boolean state in an other class :

// Déplacement
Player.prototype.move = function() {

    if (controler.left) {
        this.posHorizontal -= this.speed;
    }
}

this isn't working ! When I display the state in the controller class it return 'true' but not in another classes. I'v got no error but only a 'false' displayed (i've tried with console.log but no way).

Thanks for help !

Karz
  • 557
  • 1
  • 6
  • 22

1 Answers1

0

When the browser calls onKeyDown and onKeyUp methods, after the events happen, the this keyword inside the functions points to the document not to the Controller instance.

change the lines

document.onkeydown = this.onKeyDown;
document.onkeyup = this.onKeyUp;

to

document.onkeydown = this.onKeyDown.bind(this);
document.onkeyup = this.onKeyUp.bind(this);

and it should fix the issue.

Rafael
  • 18,349
  • 5
  • 58
  • 67