Add a controller to your game in 5 minutes
Your game already works with a keyboard. By the end of this page it also works with Xbox, PlayStation and
Switch controllers, the controller vibrates when something happens in the game, and a test proves it without a
controller plugged in. The game’s own code stays as it is: @gamepadly/sdk/bridge reads the controller and presses
the keys the game already listens for.
1. Install
Section titled “1. Install”npm install @gamepadly/sdkNo bundler? Import from https://esm.sh/@gamepadly/sdk@0.9.0/browser in a <script type="module"> instead.
See Installation.
2. Find how your game reads the keyboard
Section titled “2. Find how your game reads the keyboard”Search the game’s code for keydown and note two things:
- Which keys it reads, for example the arrow keys and Space, or WASD, J and K.
- Where it listens. This is the step that most often goes wrong:
| The game calls | Pass to the bridge |
|---|---|
window.addEventListener('keydown', …) |
nothing |
document.addEventListener('keydown', …) |
nothing |
canvas.addEventListener('keydown', …) |
keyTarget: canvas |
The bridge dispatches its events on keyTarget, which defaults to document, and they bubble up from there to
window. Events never travel down to an element, so a game that listens on its canvas needs keyTarget: canvas.
(Before version 0.7.0 the default was window. On an older version, pass keyTarget: document.)
The events carry code, key and keyCode, so it does not matter which of the three the game checks.
3. Map the controller to those keys
Section titled “3. Map the controller to those keys”import { createGamepadly } from '@gamepadly/sdk';import { createKeyMouseBridge } from '@gamepadly/sdk/bridge';
const hub = createGamepadly();const bridge = createKeyMouseBridge({ player: hub, profile: { name: 'My game', keys: { up: 'KeyW', down: 'KeyS', left: 'KeyA', right: 'KeyD', // D-pad 'ly-': 'KeyW', 'ly+': 'KeyS', 'lx-': 'KeyA', 'lx+': 'KeyD', // left stick south: 'Space', // A on Xbox, Cross on PlayStation, B on Nintendo west: 'KeyJ', // X / Square / Y r2: { code: 'KeyK', threshold: 0.3 }, // right trigger, pressed past 30% start: 'Escape', }, },});bridge.start();Each entry maps a controller input to a KeyboardEvent.code.
Inputs are button names by position (south, east, west, north, l1, r1, start, select, D-pad
up / down / left / right; see Buttons and layouts), the analog
triggers l2 / r2, and stick directions lx-, lx+, ly- (up), ly+ (down) and the same for the right stick.
A value can also be a rule: { code, threshold, repeatMs, hapticOnPress }, or an array to press several keys.
If the game happens to use one of these layouts, a built-in profile saves the typing:
profile |
Keys it presses |
|---|---|
'platformer' |
Arrow keys; south → Space, west → Z, east → X, R2 → Shift, start → Escape |
'arcade-4way' |
Arrow keys with auto-repeat for grid and puzzle games; south → Space, east → Escape, start → Enter |
'racing' |
Left / right arrows to steer, R2 → ArrowUp, L2 → ArrowDown; south → Space, west → Shift, start → Escape |
'twin-stick' |
WASD; south → Space, west → R, start → Escape; the right stick moves a virtual mouse cursor and R2 / L2 click |
Games aimed with the mouse
Section titled “Games aimed with the mouse”Add a pointer to the profile and the right stick moves a virtual cursor that sends pointer and mouse events:
import { createGamepadly } from '@gamepadly/sdk';import { createKeyMouseBridge } from '@gamepadly/sdk/bridge';
const hub = createGamepadly();const bridge = createKeyMouseBridge({ player: hub, pointerTarget: canvas, // the element the game listens on for mouse events onCursorUpdate: (cursor) => drawCrosshair(cursor.x, cursor.y), profile: { name: 'My shooter', keys: { 'lx-': 'KeyA', 'lx+': 'KeyD', 'ly-': 'KeyW', 'ly+': 'KeyS' }, pointer: { stick: 'right', clickButton: 'r2', secondaryClickButton: 'l2' }, },});4. Make the game’s events felt
Section titled “4. Make the game’s events felt”Key presses only tell the bridge what the player did. To feel what happened in the game, call triggerHaptic
from the game’s own code where it handles hits, shots and pickups:
function onPlayerHit(fromLeft: boolean) { bridge.triggerHaptic('heavy_impact', { pan: fromLeft ? -0.6 : 0.6 });}function onCoin() { bridge.triggerHaptic('click');}pan runs from -1 (left) to 1 (right). Good starting points:
| Moment | Preset |
|---|---|
| Menu and UI | 'click', 'ratchet' |
| Shooting | 'recoil' |
| Taking damage | 'heavy_impact' |
| Hitting a wall | 'wall_hit' |
| Dash or speed boost | 'boost' |
| Invalid action | 'error_buzz' |
Each call picks the best output the controller has and returns which one played. See Haptics.
5. Show players what to press
Section titled “5. Show players what to press”Browsers hide controllers from a page until the player presses a button, so show a hint until one appears, and name buttons the way they are printed on the player’s controller:
import { getButtonLabel } from '@gamepadly/sdk';
function renderControllerHint() { const connected = hub.getSlots().length > 0; const brand = hub.active.getCapabilities().identity.brand; // 'xbox' | 'sony' | 'nintendo' | ... hint.textContent = connected ? `Press ${getButtonLabel('south', brand)} to jump` // "A", "Cross" or "B" : 'Press any button on your controller';}renderControllerHint();hub.onCapabilitiesChange(renderControllerHint);6. Optional: DualSense triggers and Switch Pro HD Rumble
Section titled “6. Optional: DualSense triggers and Switch Pro HD Rumble”Over the standard Gamepad API every controller works, with rumble. Adaptive triggers, gyro and touchpad on a DualSense, and HD Rumble on a Switch Pro Controller, need one WebHID permission in desktop Chrome or Edge. Offer a button, because the browser only shows its device picker after a click:
connectButton.hidden = !('hid' in navigator);connectButton.addEventListener('click', () => void hub.connectWebHID());void hub.reconnectAuthorized(); // reconnects controllers the player approved before, without a promptAdd trigger effects to the profile and the bridge applies them while it runs:
bridge.setProfile({ name: 'My game', keys: { south: 'Space', r2: { code: 'KeyK', threshold: 0.3 } }, triggers: { right: 'weapon' }, // a resistance wall that gives way, like a gun trigger});See Adaptive triggers for every effect.
7. Test it without a controller
Section titled “7. Test it without a controller”createMockPlayerHandle() is a fake controller you press in code. This test runs in Vitest or Jest in plain
Node, with no browser environment:
import { describe, expect, it } from 'vitest';import { createKeyMouseBridge } from '@gamepadly/sdk/bridge';import { createMockPlayerHandle } from '@gamepadly/sdk/game';
describe('controller support', () => { it('presses Space for the south button and arrows for the left stick', () => { const pad = createMockPlayerHandle({ brand: 'xbox' }); const target = new EventTarget(); const pressed: string[] = []; target.addEventListener('keydown', (e) => pressed.push((e as KeyboardEvent).code));
const bridge = createKeyMouseBridge({ player: pad, profile: 'platformer', keyTarget: target, pointerTarget: null, autoRaf: false, // drive it with tick() instead of requestAnimationFrame }); bridge.start();
pad.state.buttons.cross = true; // the mock state uses base names: south is `cross` bridge.tick(1 / 60, 16); pad.state.lx = -1; bridge.tick(1 / 60, 32);
expect(pressed).toEqual(['Space', 'ArrowLeft']); expect(bridge.triggerHaptic('heavy_impact')).toBe('impulse_triggers'); // what an Xbox controller plays bridge.dispose(); });});Base names in mock state: cross (south), circle (east), square (west), triangle (north), options (start),
create (select). Sticks are lx, ly, rx, ry from -1 to 1; triggers l2, r2 from 0 to 1.
8. Clean up
Section titled “8. Clean up”If the game can be torn down without a page reload (a single-page app route, a React component, a restart), release everything:
bridge.dispose(); // releases held keys and resets triggershub.dispose(); // stops rumble and resets every controllerOn a normal page close the SDK resets rumble and triggers by itself.
Next steps
Section titled “Next steps”- Use with AI agents: prompts and project rules for coding agents.
- Start a new game: for code you write yourself, action maps are more flexible than synthetic key presses.
- Keyboard game example: a complete before-and-after in one HTML file.