How to use addEventListener in a game loop

  addeventlistener, game-loop, javascript

I’m relatively new to Javascript, so please bear with me if this is a rather trivial problem.

I’m trying to make a game where I can control a player with the arrow keys. A simplified version of the code (which doesn’t work) looks like the following:

class Player {
  constructor(X) {
    this.X = X;
  }
}

class Game {
  constructor() {
    this.gamePlayer = new Player(0);
    window.requestAnimationFrame(() => this.gameLoop());
  }

  playerMovement(event) {
    switch (event.code) {
      case "ArrowLeft":
        console.log(this.gamePlayer.X);
        this.gamePlayer.X -= 1;
        break;
      case "ArrowRight":
        console.log(this.gamePlayer.X);
        this.gamePlayer.X += 1;
        break;
    }
  }

  gameLoop() {
    window.addEventListener("keydown", this.playerMovement);

    setTimeout(() => {
      window.requestAnimationFrame(() => this.gameLoop());
    }, 50);
  }
}

window.onload = () => {
  let game = new Game();
};

So, basically, I’d like to control gamePlayer.X with the left and right arrow keys. However, with the above code, whenever I press an arrow key, I get the following error message:

Uncaught TypeError: Cannot read property ‘X’ of undefined at playerMovement

So my question is, why can’t it read this.gamePlayer.X inside the function playerMovement? How should I change the code to make it work?

Source: Ask Javascript Questions

LEAVE A COMMENT