I followed a tutorial for class to make a 'frogger-like' game. I've been provided the following event listener to control player movement with the arrow keys:
document.addEventListener('keyup', function(e) {
let allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
player.handleInput(allowedKeys[e.keyCode]);
});
I'm trying to write some code to get the left,up,right,down movement functionality working. In the tutorial they use a switch statement. However, I don't want to copy everything in the tutorial(I won't learn that way). I was thinking I could globally scope 'allowKeys' and set a variable but that doesn't seem to work(or I'm doing it wrong....) Can anybody offer any suggestions? The following is where handleInput() is called....
class Player extends Entity{
constructor() {
super();
this.sprite += 'char-boy.png';
this.x = 2;
this.y = 5;
}
update(dt){
}
handleInput(input){
//<---------code goes here
}
}
(this is being rendering in cavnas)
If you're using ES6 modules to create and import classes you'll need to attach the allowedKeys variable to the window object so that you can access it inside of the Player class. Something like this:
window.allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
Then in the player class you'll be able to dereference the window variable to pull out the value:
const allowedKeys = window.allowedKeys;
class Player extends Entity {...
Then you can reference that variable from inside the class. Not the best way to do this though.