Input
Bind named actions to any mix of keys, pointer and gamepad, then ask about actions, not devices.
ts
▶ Run in playgroundimport { 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();down(action): held nowpressed(action)/released(action): changed this step. Taps shorter than a frame are never missed.axis(negative, positive): −1, 0 or 1
Binding names
| Source | Names |
|---|---|
| Keyboard | KeyboardEvent.code values: Space, KeyZ, ArrowUp… These are layout-independent |
| Pointer | Pointer (mouse button, touch or pen) |
| Gamepad buttons | PadA PadB PadX PadY PadL1 PadR1 PadL2 PadR2 PadSelect PadStart PadL3 PadR3 PadUp PadDown PadLeft PadRight |
| Left stick | PadStickUp 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
zonecentres wherever the thumb lands in that rectangle.touch.stick.xandyare 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.pointershould skip it whiletouch.holding. draw()draws plain translucent circles. How the controls look is the game's call: readtouch.stickandtouch.buttonsto draw your own.- Tests and agents drive them with
input.pointer.touchStart(id, x, y),touchMoveandtouchEnd, and replays record them like any touch.