Skip to content

Input ​

Bind named actions to any mix of keys, pointer and gamepad, then ask about actions, not devices.

ts
import { Input } from "@debuffjp/input";

const input = new Input(game, {
  bindings: {
    left: ["ArrowLeft", "KeyA", "PadLeft", "PadStickLeft"],
    right: ["ArrowRight", "KeyD", "PadRight", "PadStickRight"],
    jump: ["Space", "PadA", "Pointer"],
  },
});

// in update(dt)
player.vx = input.axis("left", "right") * speed;
if (input.pressed("jump")) jump();
▶ Run in playground
  • down(action): held now
  • pressed(action) / released(action): changed this step. Taps shorter than a frame are never missed.
  • axis(negative, positive): −1, 0 or 1

Binding names ​

SourceNames
KeyboardKeyboardEvent.code values: Space, KeyZ, ArrowUp… These are layout-independent
PointerPointer (mouse button, touch or pen)
Gamepad buttonsPadA PadB PadX PadY PadL1 PadR1 PadL2 PadR2 PadSelect PadStart PadL3 PadR3 PadUp PadDown PadLeft PadRight
Left stickPadStickUp PadStickDown PadStickLeft PadStickRight
On-screen controls (TouchControls, from 0.26)TouchStickUp TouchStickDown TouchStickLeft TouchStickRight, and Touch<name> for each button: TouchA, TouchJump…

input.pointer gives the primary pointer's logical x/y and every active touch in touches.

On-screen touch controls ​

From 0.26, TouchControls puts a stick and buttons on the screen for phones and tablets. They feed the same actions as keys and pads, so the game reads input.down("jump") whatever the player uses:

ts
import { Input, TouchControls } from "@debuffjp/input";

const input = new Input(game, {
  bindings: {
    left: ["ArrowLeft", "PadStickLeft", "TouchStickLeft"],
    right: ["ArrowRight", "PadStickRight", "TouchStickRight"],
    jump: ["Space", "PadA", "TouchA"],
  },
});
const touch = new TouchControls(game, input, {
  stick: { x: 40, y: -40, zone: [0, 0, 160, -1] }, // floating: centres where the thumb lands on the left
  buttons: { A: { x: -32, y: -32 } },              // 32 units in from the bottom-right corner
});

// in render, outside draw.withCamera:
touch.draw(draw);
  • Positions are in logical units. A negative one counts from the right or bottom edge, so the layout holds when scale: "expand" changes the size.
  • A stick with a zone centres wherever the thumb lands in that rectangle. touch.stick.x and y are analog, from -1 to 1.
  • A contact belongs to the control it started on until the finger lifts, so a thumb can slide off a button and keep it held.
  • They appear from the first touch, so mouse and keyboard players never see them. Pass show: "always" or "never" to change that.
  • Their contacts are also the pointer's. Code that follows input.pointer should skip it while touch.holding.
  • draw() draws plain translucent circles. How the controls look is the game's call: read touch.stick and touch.buttons to draw your own.
  • Tests and agents drive them with input.pointer.touchStart(id, x, y), touchMove and touchEnd, and replays record them like any touch.