Unit 7 ยท JavaScript

7.10.3Key event handling

Keep a record of which keys are currently held down, then read it in the update step. This allows smooth movement and pressing two keys together (diagonals).

JavaScript
const keys = {};

window.addEventListener('keydown', e => {
  keys[e.code] = true;                         // e.code examples: ArrowLeft, KeyA, Space
  if (['Space', 'ArrowUp', 'ArrowDown'].includes(e.code)) e.preventDefault(); // stop page scrolling
});
window.addEventListener('keyup', e => {
  keys[e.code] = false;
});

function handleInput(p) {
  let moving = false;
  if (keys['ArrowLeft']  || keys['KeyA']) { p.x -= p.speed; p.row = 1; moving = true; }
  if (keys['ArrowRight'] || keys['KeyD']) { p.x += p.speed; p.row = 0; moving = true; }
  if (keys['ArrowUp']    || keys['KeyW']) { p.y -= p.speed; moving = true; }
  if (keys['ArrowDown']  || keys['KeyS']) { p.y += p.speed; moving = true; }
  return moving;
}

Keep the player inside the canvas: p.x = Math.max(0, Math.min(canvas.width - p.w, p.x)); (same for y). Also handle one-time actions (shoot, restart) on keydown only, and handle touch buttons if the game should work on phones.