After following a tutorial for my class project on creating a 'frogger-like' game, I encountered a challenge with implementing player movement using arrow keys. The event listener provided in the tutorial facilitated this movement:
document.addEventListener('keyup', function(e) {
let allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
player.handleInput(allowedKeys[e.keyCode]);
});
I'm attempting to write code that enables left, up, right, and down movements without simply replicating the switch statement used in the tutorial as I believe learning requires more than imitation. I've tried using a globally scoped variable 'allowedKeys' but it didn't yield the desired results (likely due to an error on my part). Can anyone provide suggestions on a different approach? Below is the section where 'handleInput()' needs to be implemented:
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 game is rendered on canvas)