# Controllers

A controller is an [input source](https://developer.playcanvas.com/user-manual/xr/input-sources.md) that the user holds. Besides the ray, select and squeeze of every input source, it has a **grip pose**, where the user's hand holds it, and a gamepad with buttons, a trigger, a thumbstick, and usually a motor that vibrates. This page covers each, and the engine's `XrControllers` script that draws the controllers in the scene.

[Image: The left and right controllers of a Meta Quest 3, labeled with the index of each button and thumbstick axis in the gamepad: the trigger, the grip, the thumbstick, the X and Y buttons on the left controller, and the A and B buttons on the right one]

[Live example: VR Controllers](https://playcanvas.com/examples/#/xr/vr-controllers) ([source](https://github.com/playcanvas/engine/blob/main/examples/src/examples/xr/vr-controllers/example.mjs))

## The Grip Pose

`inputSource.grip` is `true` for an input source that the user holds. Its grip pose is the position and rotation of the user's closed hand around the controller. `getPosition()` and `getRotation()` return it in world space, with the [rig's](https://developer.playcanvas.com/user-manual/xr/sessions.md#the-camera-and-its-rig) transform applied, or `null` for an input source without a grip pose. To put something in the user's hand, copy the pose to it every frame:

```javascript
app.on('update', () => {
    for (const inputSource of app.xr.input.inputSources) {
        if (inputSource.grip && inputSource.handedness === XRHAND_RIGHT) {
            // Keep the flashlight in the user's right hand
            flashlight.setPosition(inputSource.getPosition());
            flashlight.setRotation(inputSource.getRotation());
        }
    }
});
```

The grip pose's origin is at the center of the user's curled fingers. Its negative Z axis points along the controller's handle, out past the thumb, and its positive Y axis points roughly back along the user's arm. Its X axis points out of the back of the right hand, and into the back of the left one. Model objects for the hand to match, or make them children of an entity that follows the grip, offset as they need to be.

`getLocalPosition()` and `getLocalRotation()` return the same pose relative to the rig. Like the ray, these methods return vectors and quaternions that the input source reuses.

Tracked hands have no grip pose. Use the joints of a [hand](https://developer.playcanvas.com/user-manual/xr/hand-tracking.md#joints) instead.

## Controller Models

The `XrControllers` script draws a model of each controller and tracked hand, and moves it every frame. [Getting Started](https://developer.playcanvas.com/user-manual/xr/using-webxr.md#your-first-vr-scene) adds it to the rig in engine code, the Editor, React and Web Components. When an input source is added, the script looks up its [profiles](https://developer.playcanvas.com/user-manual/xr/input-sources.md#profiles), in order, in the WebXR Input Profiles assets, and loads the model of the first one it finds for that hand. It removes the model when the input source goes, and hides it while the device doesn't track it, such as while the system menu is open.

The script loads profiles and models from the jsDelivr CDN. To serve them yourself, for example to keep working offline, copy the `dist/profiles` folder of the [`@webxr-input-profiles/assets`](https://www.npmjs.com/package/@webxr-input-profiles/assets) npm package to your server, and set the script's `basePath` attribute to its URL:

```javascript
rig.script.create(XrControllers, {
    properties: {
        basePath: '/assets/webxr-input-profiles'
    }
});
```

It fires two application events. `xr:controller:add` is passed the input source and the entity of its model, once the model has loaded, and `xr:controller:remove` is passed the input source:

```javascript
app.on('xr:controller:add', (inputSource, entity) => {
    console.log(`Showing the ${inputSource.handedness} ${inputSource.hand ? 'hand' : 'controller'}`);
});
```

Set the script's `visible` property to `false` to hide every model, for example while the user holds a tool that takes the controller's place. To draw your own models instead, leave the script out, add a model for each input source in an `add` handler, and move it to the grip pose in `update`, as the flashlight example does.

The script only draws input sources that are added after it starts. Add it before the session starts.

## Buttons and Thumbsticks

`inputSource.gamepad` is a [`Gamepad`](https://developer.mozilla.org/docs/Web/API/Gamepad) object with the state of the controller's buttons and thumbstick, or `null` for an input source without one. Its `mapping` is `'xr-standard'`, which fixes the meaning of the first entries of its `buttons` and `axes` arrays:

| Index | `buttons` | `axes` |
| --- | --- | --- |
| 0 | The trigger, which selects | The touchpad's X |
| 1 | The grip, which squeezes | The touchpad's Y |
| 2 | The touchpad | The thumbstick's X, from -1 (left) to 1 (right) |
| 3 | The thumbstick, pressed down | The thumbstick's Y, from -1 (forward) to 1 (back) |

An input that the controller doesn't have is a placeholder that is never pressed and reads 0, and those at the end of an array are left out. The controller's profile lists what comes after index 3. On a Meta Quest controller, buttons 4 and 5 are A and B on the right controller, and X and Y on the left one.

Each button has `pressed`, `touched` and `value`, which runs from 0 to 1 for the trigger and the grip. The browser updates the gamepad every frame, but fires events only for the select and squeeze. For other buttons, compare their state with the previous frame's:

```javascript
const wasPressed = new Map();

app.on('update', () => {
    for (const inputSource of app.xr.input.inputSources) {
        const gamepad = inputSource.gamepad;
        if (!gamepad) continue;

        // A on the right controller, or X on the left one
        const pressed = gamepad.buttons[4]?.pressed ?? false;
        if (pressed && !wasPressed.get(inputSource)) {
            console.log(`Pressed button 4 (${inputSource.handedness})`);
        }
        wasPressed.set(inputSource, pressed);

        // The thumbstick, ignoring small movements around its center
        const x = gamepad.axes[2] ?? 0;
        const y = gamepad.axes[3] ?? 0;
        if (Math.hypot(x, y) > 0.2) {
            console.log(`Thumbstick at ${x.toFixed(2)}, ${y.toFixed(2)} (${inputSource.handedness})`);
        }
    }
});
```

The `?.` and `??` operators give `false` and 0 for buttons and axes that the gamepad leaves out. Tracked hands can have a gamepad too: on a Meta Quest, a hand's button 0 is its pinch, and it has no axes. Check for the buttons and axes that you use, rather than taking a gamepad to mean a controller.

## Haptics

A controller that can vibrate lists its motors in its gamepad's `hapticActuators`. A pulse takes an intensity, from 0 to 1, and a duration in milliseconds:

```javascript
// A short buzz on each select
app.xr.input.on('select', (inputSource) => {
    inputSource.gamepad?.hapticActuators?.[0]?.pulse(0.6, 50);
});
```

Not every browser and controller supports haptics, so check that the actuator is there before you use it, as above. Keep pulses short and use them to confirm actions, such as a button press or picking something up.

## Velocity

`inputSource.getLinearVelocity()` returns a controller's velocity, the direction and speed it is moving in, as a vector in world space in meters per second. It returns `null` until the velocity is known. The engine uses the velocity that the browser reports, or estimates one from the controller's movement over recent frames. Use it to throw what the user lets go of. See [Throwing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md#throwing).

The velocity is the controller's movement in the room. It doesn't include the movement of the rig, so add the rig's own velocity if it moves while the user throws. Tracked hands have no velocity, as they have no grip pose.

## See Also

- [Input Sources](https://developer.playcanvas.com/user-manual/xr/input-sources.md) - Rays, select and squeeze, handedness and profiles
- [Hand Tracking](https://developer.playcanvas.com/user-manual/xr/hand-tracking.md) - Tracked hands and their joints
- [Pointing and Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md) - Grabbing, carrying and throwing objects
- [WebXR Input Profiles](https://github.com/immersive-web/webxr-input-profiles) - The profile registry and controller models
