First question here. Im trying to create a small game and i have my character object containing some attributes as well as functions. When trying to implement a playerMove function to get my rectangle to move, i’m getting the “playerMove” is not defined error from the addEventlistener call to the function. What am I doing wrong here?
Is my way of thinking even possible? Should the eventlistener be in the main game file and pass the event to the character function instead?
Below is the code for the character object:
'use strict';
import Display from './gamearea.js';
import { gameArea } from './gamearea.js';
class Character {
constructor (name, race, weapon) {
this.name = name;
this.race = race;
this.weapon = weapon;
this.locationX = 0;
this.locationY = 125;
this.characterWidth = 25;
this.characterHeight = 12.5;
this.color = "red";
}
sayHello() {
console.log(`I'm named ${this.name}. I'm a ${this.race} using a ${this.weapon}`);
}
drawCharacter() {
let ctx = gameArea.getContext('2d');
ctx.fillStyle = this.color;
ctx.fillRect(this.locationX, this.locationY, this.characterWidth, this.characterHeight);
document.gameArea.appendChild(ctx);
}
//Eventlisteners for keydown movement
input = document.addEventListener("keydown", (e) => {playerMove(e)});
playerMove(directionInput) {
console.log(directionInput.key);
if (directionInput.key === 'w') {
this.locationY -= 5;
}
}
}
export default Character;
I’ve tried placing the eventlistener in the mainGame file and call the the function from there, but I cant get to work.