...

/

JS: Game Player Movement

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.

svg viewer
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 controller
keyboardController.left = status;
} else if (event.keyCode == 38) { //left controller
keyboardController.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 ...

Access this course and 1200+ top-rated courses and projects.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy