Input Manager
Keyboard, mouse, touch and gamepad read as named actions (“jump”, “left”), so game code never checks keys directly.
Files: input-manager.js (the component, no dependencies) and input-manager.test.mjs (9 tests).
Copy input-manager.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createInput } from "./input-manager.js";
const input = createInput({
canvas,
bindings: { left: ["ArrowLeft", "KeyA", "pad:14"], right: ["ArrowRight", "KeyD", "pad:15"], jump: ["Space", "pad:0"], fire: ["mouse:0", "KeyJ", "pad:2"] },
axes: { moveX: { neg: "left", pos: "right", pad: 0 } },
});
function frame(dt) {
input.update(); // once per frame, before game code
player.vx = input.axis("moveX") * 200;
if (input.pressed("jump")) player.jump();
}
API
createInput({ target, canvas, bindings, axes, deadzone, gamepads }) → inputinput.update()work out this frame’s presses and releases; read gamepadsinput.isDown(action)held nowinput.pressed(action)went down this frame (taps shorter than a frame still count)input.released(action)went up this frameinput.axis(name)-1..1: analog stick or touch stick if moved, else the two digital actionsinput.setVirtual(action, down)for on-screen buttons (see Touch Controller)input.setAxis(name, value)for on-screen sticks; null to clearinput.rebind(action, codes)change a binding; input.bindings() returns a copyinput.pointer{ x, y, down, type } in canvas pixels-
input.lastDevice“keyboard”“mouse” “touch” “gamepad” (for showing the right button hints) input.destroy()
Codes: KeyboardEvent.code (“KeyA”, “Space”), “mouse:0..2”, “pad:N” (standard layout: 0 A, 1 B, 2 X, 3 Y, 9 start, 12-15 d-pad), “pad:axisN+” / “pad:axisN-“.
Engines
| Engine | Notes |
|---|---|
| Vanilla | yes, made for it. |
| Phaser | yes. Give it the game canvas and skip Phaser’s keyboard plugin, or use both. |
| PixiJS | yes. Pass app.canvas (app.view in v7). |
| Three.js | yes. Pass renderer.domElement. Pointer lock games read movementX themselves. |
Tests
Node tests with fake events: bindings, same-frame taps, key repeat, blur, gamepad buttons and sticks, deadzone, virtual buttons, rebinding, pointer position.
Run them with node --test toolkit/components/input-manager/ (Node 20 or newer, nothing to install).