I am fairly new to coding and I have been constantly been coming upon one problem. When making a game, such as snake or pong, I tend to use an event listener to listen for a keydown event such as : document.body.addEventListener("keydown", moveSnake);
. I then go onto declare the function moveSnake :
function moveSnake(event){
switch(event.keyCode){
case 87:
break;
case 83:
break;
case 65:
break;
case 68:
break;
default:
break;
}
}
I understand there is no code telling the snake what to do yet. Once I do this I get a reoccurring issue. My program stops, and I get an error message in my console that says : Cannot read properties of undefined (reading 'keyCode')
. I am using the latest version of google chrome and if someone could tell me what I am doing wrong it would be much appreciated. I have tried declaring the keyCode as a variable, and many other suggestions I have found randomly online but nothing as worked. Thank you!
CodePudding user response:
The .keyCode has been deprecated due to inconsistency on browsers. (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode)
You can try with the .code, which names the keys as "ArrowUp", "ArrowLeft", "ArrowRight" and "ArrowDown".