Previous 16 Next


Keyboard controls are used when playing on PC.

A keyboard with many buttons
import { Controller } from "./Controller"

export class KeyController {
    controller: Controller,
    leftKeys: ReadonlyArray<string>,
    rightKeys: ReadonlyArray<string>,
    actionButton1Keys: ReadonlyArray<string>,
    actionButton2Keys: ReadonlyArray<string>,
  ) {
    window.addEventListener("keydown", keyboardEvent => {
      if (keyboardEvent.repeat) return
      else if (leftKeys.includes(keyboardEvent.code)) controller.pressLeft()
      else if (rightKeys.includes(keyboardEvent.code)) controller.pressRight()
      else if (actionButton1Keys.includes(keyboardEvent.code)) controller.pressActionButton1()
      else if (actionButton2Keys.includes(keyboardEvent.code)) controller.pressActionButton2()

    window.addEventListener("keyup", keyboardEvent => {
      if (leftKeys.includes(keyboardEvent.code)) controller.releaseLeft()
      else if (rightKeys.includes(keyboardEvent.code)) controller.releaseRight()
      else if (actionButton1Keys.includes(keyboardEvent.code)) controller.releaseActionButton1()
      else if (actionButton2Keys.includes(keyboardEvent.code)) controller.releaseActionButton2()

The class is passed arrays of strings that contain keycodes that should cause the function on the contoroller to be called. This makes it easy to remapping controls since we can just change the values that are in the array from the outside.

To capture events we add an event listener on keyup and keydown events.


Previous 16 Next