Touch Controller
On-screen controls for phones: a thumb stick that appears where the thumb lands and buttons on the other side, with several fingers at once. They feed the Input Manager, so game code doesn’t change.
Files: touch-controller.js (the component, no dependencies) and touch-controller.test.mjs (5 tests).
Copy touch-controller.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createInput } from "../input-manager/input-manager.js";
import { createTouchControls } from "./touch-controller.js";
const input = createInput({ canvas, bindings, axes: { moveX: { neg: "left", pos: "right" }, moveY: { neg: "up", pos: "down" } } });
const touch = createTouchControls({
element: canvas, input,
stick: { area: "left", axes: ["moveX", "moveY"], actions: { left: "left", right: "right", up: "up", down: "down" } },
buttons: [{ action: "jump", x: -70, y: -80, r: 40, label: "A" }, { action: "fire", x: -160, y: -50, r: 34, label: "B" }],
});
function frame() { ...; touch.draw(ctx); } // draws only once the player has touched the screen
API
createTouchControls({ element, input, stick, buttons, radius, show }) → touchstick: { area: “left” | “right” | “full” | { x, y, w, h } (fractions), axes: [xName, yName], actions: { left, right, up, down }, threshold } buttons: x and y in CSS pixels; negative counts from the right or bottom edge; r = radius (keep at least 28 for thumbs)touch.stick → { active, x, y } (-1..1)touch.visibletrue after the first touch (or show: “always”)touch.draw(ctx, { scale })translucent stick and buttons; scale = canvas pixels per CSS pixel (default: worked out from the element)touch.layout() → [{ action, x, y, r }] in CSS pixels, for drawing your owntouch.destroy()
The element should have CSS touch-action: none so the page doesn’t scroll or zoom.
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes; give it the canvas the game draws to. With Phaser or Pixi, draw with layout() and stick instead of draw(ctx). |
Tests
Node tests with fake pointer events: stick direction and strength, deadzone, the stick only in its area, buttons with several fingers, a finger sliding off a button, pointer cancel, showing after first touch.
Run them with node --test toolkit/components/touch-controller/ (Node 20 or newer, nothing to install).