0

How do you refer to a object in an constructor inside the same class in another function? I have tried console logging the different keystrokes, which seems to be working. The thing that is not working is adding and subtracting from this.x and this.y. And also it seems the drawChar(this.x,this.y) is not working as well. Here is the code:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var w = (canvas.width = window.innerWidth);
var h = (canvas.height = window.innerHeight);

function drawChar(x, y) {
  ctx.fillStyle = `black`;

  ctx.fillRect(x, y, 20, 20);
}

class Character {
  constructor() {
    this.x = w / 2;
    this.y = h / 2;
  }

  move(event) {
    let k = event.keyCode;

    if (k == 87) {
      this.y = this.y - 5;
    }

    if (k == 83) {
      this.y = this.y + 5;
    }

    if (k == 68) {
      this.x = this.x + 5;
    }

    if (k == 65) {
      this.x = this.x - 5;
    }

    drawChar(this.x, this.y);

  }
}

let player1;
player1 = new Character();

document.addEventListener("keydown", player1.move);
Blank
  • 33
  • 5
  • 2
    You need `document.addEventListener("keydown", player1.move.bind(player1));` or `document.addEventListener("keydown", event => player1.move(event));` But the best option would be to read the linked question and wrap your head around the answer. :) – Yury Tarabanko Dec 22 '18 at 18:54
  • Thanks, will do :thumps up emoji: – Blank Dec 22 '18 at 19:00

0 Answers0