# Add a controller to your game in 5 minutes

> Make an existing keyboard and mouse web game playable with Xbox, PlayStation and Switch controllers in about ten lines, without changing the game's code, then add haptics and a test that runs without a controller.

Source: https://gamepadly.com/sdk/start/add-controller

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.

> **Using a coding agent?**
> Give it this prompt and it will follow the same steps:
> `Read https://gamepadly.com/sdk/llms.txt, then add controller support to this game with @gamepadly/sdk.`
> See [Use with AI agents](https://gamepadly.com/sdk/start/ai-agents).

## 1. Install

```bash
npm install @gamepadly/sdk
```

No bundler? Import from `https://esm.sh/@gamepadly/sdk@0.9.0/browser` in a `<script type="module">` instead.
See [Installation](https://gamepadly.com/sdk/start/installation).

## 2. Find how your game reads the keyboard

Search the game's code for `keydown` and note two things:

1. **Which keys it reads**, for example the arrow keys and Space, or WASD, J and K.
2. **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

```ts
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`](https://developer.mozilla.org/en-US/docs/Web/API/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](https://gamepadly.com/sdk/guides/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

Add a `pointer` to the profile and the right stick moves a virtual cursor that sends pointer and mouse events:

```ts
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

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:

```ts
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](https://gamepadly.com/sdk/guides/haptics).

## 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:

```ts
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

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:

```ts
connectButton.hidden = !('hid' in navigator);
connectButton.addEventListener('click', () => void hub.connectWebHID());
void hub.reconnectAuthorized(); // reconnects controllers the player approved before, without a prompt
```

Add trigger effects to the profile and the bridge applies them while it runs:

```ts
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](https://gamepadly.com/sdk/guides/adaptive-triggers) for every effect.

## 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:

```ts
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

If the game can be torn down without a page reload (a single-page app route, a React component, a restart),
release everything:

```ts
bridge.dispose(); // releases held keys and resets triggers
hub.dispose(); // stops rumble and resets every controller
```

On a normal page close the SDK resets rumble and triggers by itself.

## Next steps

- [Use with AI agents](https://gamepadly.com/sdk/start/ai-agents): prompts and project rules for coding agents.
- [Start a new game](https://gamepadly.com/sdk/start/quick-start): for code you write yourself, action maps are more flexible than
  synthetic key presses.
- [Keyboard game example](https://gamepadly.com/sdk/examples#keyboard-game-bridge): a complete before-and-after in one HTML file.
