Intermediate • Lesson 7

Input Controls: Keyboard, Mouse, Gamepad & Touch

Every input device feels different. Instead of cramming everything together, this guide gives Keyboard, Mouse, Gamepad (with interactive calibration!), and Touch their own dedicated explanation and live canvas.

1. Keyboard Input & Canvas Focus

On a web page, a <canvas> shares space with links and text boxes—so browsers only send keyboard presses when the canvas is focused. Maverick draws a built-in Focus Indicator (● FOCUSED vs ○ CLICK CANVAS TO FOCUS) and maps keys via this.Input.bindAction().

this.Input.bindAction('left',  ['ArrowLeft', 'a', 'A']);
this.Input.bindAction('right', ['ArrowRight', 'd', 'D']);
this.Input.bindAction('up',    ['ArrowUp', 'w', 'W']);
this.Input.bindAction('down',  ['ArrowDown', 's', 'S']);
PoC 1 — Keyboard Movement & Focus Indicator
Click the canvas to focus it, then move the cyan square with WASD or Arrow Keys.

2. Mouse Input (Clicks & Aiming Reticle)

Bind mouse buttons inside bindAction() or override onMouseDown(e) to receive exact logical coordinates automatically scaled for CSS size and DPR.

this.Input.bindAction('shoot', [{ mouseButton: GameMouseButtons.left }]);
onMouseDown(e: GameMouseEvent): void {
  if (e.button === GameMouseButtons.right) this.moveTarget = { x: e.x, y: e.y };
}
PoC 2 — Mouse Aiming, Left-Click Marker & Right-Click Move
Move mouse to aim, Left-Click to drop an amber marker, Right-Click to move the hero!

3. Gamepad / Controller + Interactive Calibration

Plug in any Xbox, PlayStation, or Switch Pro controller (USB or Bluetooth). Different controllers number their buttons differently, so let players calibrate Up, Down, Left, Right, and Jump and bind those button indices directly with { gamepadButton }:

this.Input.bindAction('up',    [{ gamepadButton: 12 }]);
this.Input.bindAction('down',  [{ gamepadButton: 13 }]);
this.Input.bindAction('left',  [{ gamepadButton: 14 }]);
this.Input.bindAction('right', [{ gamepadButton: 15 }]);
this.Input.bindAction('jump',  [{ gamepadButton: 0 }]);
PoC 3 — Attach a Gamepad, Calibrate Buttons & Play Platformer
Attach a gamepad and press any button to wake it up, or click "Start Gamepad Calibration" to map Up, Down, Left, Right, and Jump!

4. Mobile Touch & Virtual Joystick

For phones and tablets, bind touch zones with { touchRect } or read a smooth -1..1 virtual thumbstick with this.Input.getVirtualStick(cx, cy, radius).

const stick = this.Input.getVirtualStick(80, 140, 45);
if (stick.active) player.Config.pos!.x += stick.x * 180 * dt;
PoC 4 — Touch / Drag Virtual Thumbstick & Jump Zone
Touch or drag inside the left circle (virtual thumbstick) to steer, and tap the right button to pulse!