# Input Sources

An input source is anything the user points with or acts through in an XR session: a controller in each hand, a tracked hand, a tap on a phone's screen, or a look and a pinch on an Apple Vision Pro. The engine represents each one as an [`XrInputSource`](https://api.playcanvas.com/engine/classes/XrInputSource.html), with a ray that points into the scene and a primary action, the **select**. Code that works with rays and selects works with every kind of input source.

[Image: A user in a headset seen from outside. A controller in the right hand points a ray at a box, with its grip axes drawn where the hand holds it. The tracked left hand points a ray of its own from between its thumb and index finger.]

This page covers what all input sources have in common. [Controllers](https://developer.playcanvas.com/user-manual/xr/controllers.md) and [Hand Tracking](https://developer.playcanvas.com/user-manual/xr/hand-tracking.md) cover what only controllers and hands have, and [Pointing and Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md) builds interactions from them.

## Kinds of Input Source

An input source's `targetRayMode` says what kind it is, and where its ray starts:

| `targetRayMode` | Constant | What it is | Its ray |
| --- | --- | --- | --- |
| `'tracked-pointer'` | `XRTARGETRAY_POINTER` | A controller, or a tracked hand | From the front of the controller, or from between the thumb and index finger, pointing where the user points |
| `'transient-pointer'` | | A look and a pinch on Apple Vision Pro | From between the user's eyes, toward what they looked at when they pinched |
| `'screen'` | `XRTARGETRAY_SCREEN` | A touch on a phone's screen in AR | From the screen, through the point the user touches, into the scene |
| `'gaze'` | `XRTARGETRAY_GAZE` | The user's head, on a phone in a VR viewer such as Google Cardboard | From the user's head, in the direction they face |

Controllers and hands stay for as long as the device tracks them. The other kinds are **transient**: a touch on the screen, or a pinch on an Apple Vision Pro, adds an input source when it starts and removes it when it ends. The engine has no constant for `'transient-pointer'`, so compare `targetRayMode` with the string.

A device can have more than one kind. A Meta Quest switches between controllers and tracked hands as the user puts the controllers down or picks them up. On an Apple Vision Pro, the user's hands are tracked-pointer input sources that give the position of each joint, while their selects come from the transient pointer of each look and pinch.

## Adding and Removing

`app.xr.input.inputSources` is the list of the input sources at the moment. It changes as the user picks up or puts down a controller, a hand comes into view or leaves it, or a touch starts and ends. `app.xr.input` fires `add` and `remove` as the list changes, and each input source fires `remove` when it goes:

```javascript
app.xr.input.on('add', (inputSource) => {
    console.log(`Added a ${inputSource.targetRayMode} input source (${inputSource.handedness})`);

    inputSource.once('remove', () => {
        console.log(`Removed a ${inputSource.targetRayMode} input source (${inputSource.handedness})`);
    });
});
```

Subscribe to `add` before the session starts. The input sources that are there at the start of a session are added as it starts, and when the session ends, `remove` fires for each input source that is left. Code that only starts during a session should go through `inputSources` first, and then follow `add`.

Create anything that belongs to an input source, such as a model or a laser, in the `add` handler, and destroy it on `remove`. Don't keep an input source after it's removed. A controller that reconnects comes back as a new input source, with a new `id`.

## Rays

Every input source has a ray. `getOrigin()` and `getDirection()` 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, so the ray points into the scene from wherever the rig has taken the user. To find what the user points at, test the ray against the scene:

```javascript
const ray = new Ray();

app.on('update', () => {
    for (const inputSource of app.xr.input.inputSources) {
        ray.set(inputSource.getOrigin(), inputSource.getDirection());

        // Test the ray against the bounding box of the box's mesh
        if (box.render.meshInstances[0].aabb.intersectsRay(ray)) {
            console.log(`The ${inputSource.handedness} input source points at the box`);
        }
    }
});
```

The origin and direction are vectors that the input source reuses, so copy them if you need to keep them. [Pointing and Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md#pointing) picks the closest of many objects, with bounding boxes or with physics, and draws the ray as a laser.

## Select and Squeeze

Every input source has a primary action, the **select**. Controllers and hands also have a **squeeze**, which is often used to grab things:

| Input source | Select | Squeeze |
| --- | --- | --- |
| Controller | Pull the trigger | Squeeze the grip button |
| Tracked hand | Pinch the thumb and index finger together | Make a fist |
| Look and pinch | Pinch | |
| Screen | Touch the screen | |
| Gaze | Press the viewer's button | |

Each action fires three events, both on the input source and on `app.xr.input`:

| Event | Fired when |
| --- | --- |
| `selectstart`, `squeezestart` | The action starts |
| `select`, `squeeze` | The action completes, just before it ends |
| `selectend`, `squeezeend` | The action ends, whether it completed or not |

`select` and `squeeze` fire only for an action that completes. An action that is cancelled, for example because the hand doing it leaves the view of the headset, fires only its end event. Use `select` for actions that happen once, like a mouse click, and `selectstart` and `selectend` for actions that last while the user holds them, such as aiming.

Handlers on `app.xr.input` are passed the input source first, which suits transient input sources, as they only exist for the length of their action:

```javascript
// Every select of every input source
app.xr.input.on('select', (inputSource) => {
    console.log(`Selected with a ${inputSource.targetRayMode} input source`);
});

// One input source's squeeze
app.xr.input.on('add', (inputSource) => {
    inputSource.on('squeezestart', () => {
        console.log(`Started a squeeze (${inputSource.handedness})`);
    });
});
```

The handlers on an input source are passed the browser's [`XRInputSourceEvent`](https://developer.mozilla.org/docs/Web/API/XRInputSourceEvent), and those on `app.xr.input` are passed it after the input source. While an action lasts, the input source's `selecting` or `squeezing` property is `true`, for code that runs every frame.

The browser reports a hand's pinch as its select. The engine adds the squeeze: it fires the squeeze events of a hand when its four fingers curl into a fist.

## Handedness

`handedness` is the hand that holds or is an input source: `'left'` (`XRHAND_LEFT`), `'right'` (`XRHAND_RIGHT`), or `'none'` (`XRHAND_NONE`) for one that isn't held, such as a touch on the screen or gaze. Use it to give each hand its own role. The engine's `XrNavigation` script, for example, moves the user with the left thumbstick and turns them with the right. Not everyone is right-handed, so let users swap hands for the actions that need precision.

## Profiles

`profiles` names the input source's profiles in the [WebXR Input Profiles](https://github.com/immersive-web/webxr-input-profiles/tree/main/packages/registry) registry, from the most specific to the most generic. A Meta Quest 3's controller reports:

```none
meta-quest-touch-plus, oculus-touch-v3, oculus-touch, generic-trigger-squeeze-thumbstick
```

A profile describes the input source's buttons and thumbsticks, and the registry's assets include a 3D model for each. The engine's `XrControllers` script uses them to draw a [model of each controller](https://developer.playcanvas.com/user-manual/xr/controllers.md#controller-models). Your code can use them to show instructions for the controller in the user's hand:

```javascript
app.xr.input.on('add', (inputSource) => {
    // The right controller of a Meta Quest, from the first Touch controllers on
    if (inputSource.handedness === XRHAND_RIGHT && inputSource.profiles.includes('oculus-touch')) {
        console.log('Press A to jump');
    }
});
```

New devices bring new profile names, but they list older and generic profiles after their own. Look for the profile you designed for anywhere in the list, as above, rather than only at its start, and fall back to generic instructions.

## Input and the User Interface

The rays of input sources point at [UI elements](https://developer.playcanvas.com/user-manual/user-interface/xr.md) as a mouse does. When a ray moves onto an element whose input is enabled, the element fires `selectenter`, and a select on it clicks it, so buttons and their `click` listeners work unchanged. Each input source's `elementEntity` is the entity of the element it points at, or `null`, and setting its `elementInput` to `false` keeps it away from the interface. See [UI in XR](https://developer.playcanvas.com/user-manual/user-interface/xr.md#pointing-and-selecting).

## See Also

- [Controllers](https://developer.playcanvas.com/user-manual/xr/controllers.md) - Grip poses, models, buttons, thumbsticks and haptics
- [Hand Tracking](https://developer.playcanvas.com/user-manual/xr/hand-tracking.md) - The joints of tracked hands, and gestures
- [Pointing and Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md) - Picking, grabbing and throwing objects
- [XrInputSource](https://api.playcanvas.com/engine/classes/XrInputSource.html) and [XrInput](https://api.playcanvas.com/engine/classes/XrInput.html) - API reference
