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);