JS: Game Player Movement
Learn how an object moves around in the canvas with the arrow keys.
Keyboard controllers
Our player will move by using the arrow keys on the keyboard. We will add a new method that will check the key pressed and move the player accordingly. The method for this purpose is given below.
Press + to interact
const keyboardController = (() => {document.addEventListener("keydown", inputEvent);document.addEventListener("keyup", inputEvent);const keyboardController = {right: false,left: false,up: false,any : false,};function inputEvent(event) {const status = event.type === "keydown"if (event.keyCode == 39) // up controller{keyboardController.right = status;} else if (event.keyCode == 37) { // right controllerkeyboardController.left = status;} else if (event.keyCode == 38) { //left controllerkeyboardController.up = status;event.preventDefault(); // to prevent the default functionality of event}if(status) { keyboardController.any = true } // must reset when used}return keyboardController;})();// make sure window has focus for keyboardController input.window.focus();
Player Movement
-
In
lines
...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy