Keyboard Input

TCJSgame includes built-in keyboard handling so you don’t need to write event listeners manually. The display.keys object automatically tracks which keys are currently pressed. You can simply check display.keys[keyCode] inside your update() function.

Key codes are based on standard JavaScript values: 37 = left arrow, 38 = up, 39 = right, 40 = down, and 32 = space bar. This system works well for simple control schemes and avoids the need to handle keydown and keyup events yourself.

Syntax

if (display.keys[37]) { player.x -= 2; } // left arrow

Example

const player = new Component(30, 30, "blue", 50, 50, "rect");
display.add(player);

function update() {
  if (display.keys[39]) player.x += 2; // right
  if (display.keys[37]) player.x -= 2; // left
  if (display.keys[38]) player.y -= 2; // up
  if (display.keys[40]) player.y += 2; // down
}

Notes