# Hand Tracking

On devices that track the user's hands, each hand is an [input source](https://developer.playcanvas.com/user-manual/xr/input-sources.md) with the position and rotation of each of its joints. Users can point, pinch and grab with their own hands, without controllers. Every session asks for hand tracking, so the hands are there wherever the device offers them. See [Options and Features](https://developer.playcanvas.com/user-manual/xr/sessions.md#options-and-features).

[Image: The user's tracked hands seen from the headset, with a sphere at each joint and lines joining the joints of each finger. The fingertips are orange. The joints of the left hand's pinky finger, its wrist and its thumb tip are labeled with their names.]

[Live example: XR Hands](https://playcanvas.com/examples/#/xr/xr-hands) ([source](https://github.com/playcanvas/engine/blob/main/examples/src/examples/xr/xr-hands/example.mjs))

## Hands as Input Sources

A tracked hand's input source has a `hand` property, an [`XrHand`](https://api.playcanvas.com/engine/classes/XrHand.html), which is `null` for input sources without hand tracking. A hand works like a controller in most ways:

- **Its select is a pinch** of the thumb and index finger.
- **Its squeeze is a fist.** The engine fires a hand's squeeze events when its four fingers curl into a fist.
- **Its ray starts between the thumb and the index finger**, and points ahead of the palm. The engine computes it from the joints.

A hand has no grip pose, so its `getPosition()`, `getRotation()` and `getLinearVelocity()` return `null`. Use its [joints](https://developer.playcanvas.com/user-manual/xr/hand-tracking.md#joints) instead. It can have a gamepad. On a Meta Quest, a hand's gamepad has the pinch as button 0, and no axes.

From engine 2.25, a controller can have a `hand` too. Some runtimes, such as SteamVR, pose a hand from the finger sensors of a controller. That controller keeps its grip pose, ray and squeeze. To tell a controller from a bare hand, check `grip`, which only controllers have.

A Meta Quest switches between controllers and hands as the user puts the controllers down or picks them up. The controllers' input sources are removed and the hands' are added, or the other way round, so code that follows `add` and `remove` handles both.

On an Apple Vision Pro, the hands give the poses of their joints, but don't select or squeeze. The user selects with a look and a pinch, which is a [transient input source](https://developer.playcanvas.com/user-manual/xr/input-sources.md#kinds-of-input-source) of its own.

## Joints

A hand has 25 joints: the wrist, four in the thumb and five in each finger. They are named as in the [WebXR Hand Input](https://www.w3.org/TR/webxr-hand-input-1/#skeleton-joints-section) specification:

| Part | Joints, from the wrist out |
| --- | --- |
| Wrist | `wrist` |
| Thumb | `thumb-metacarpal`, `thumb-phalanx-proximal`, `thumb-phalanx-distal`, `thumb-tip` |
| Each finger | `index-finger-metacarpal`, `index-finger-phalanx-proximal`, `index-finger-phalanx-intermediate`, `index-finger-phalanx-distal`, `index-finger-tip`, and the same for the `middle-finger`, `ring-finger` and `pinky-finger` |

`XrHand` gives the joints several ways:

| Property or method | Returns |
| --- | --- |
| `joints` | Every joint: the wrist, then each finger's joints from the thumb to the pinky |
| `fingers` | The five fingers, from the thumb (index 0) to the pinky (index 4). Each has its `joints` and its `tip` |
| `tips` | The five fingertips |
| `wrist` | The wrist joint |
| `getJointById(id)` | The joint with that name, such as `'index-finger-tip'`, or `null` |

Each joint is an [`XrJoint`](https://api.playcanvas.com/engine/classes/XrJoint.html). `getPosition()` and `getRotation()` return its pose in world space, with the [rig's](https://developer.playcanvas.com/user-manual/xr/sessions.md#the-camera-and-its-rig) transform applied. `radius` is the distance from the joint to the surface of the skin, in meters, which helps to size what you draw at the joint. `id` is its name, `finger` is its finger, or `null` for the wrist, and `isWrist` and `isTip` say what it is.

A joint's negative Z axis points along its bone, toward the fingertip, and its negative Y axis points out of the palm side of the hand.

## Drawing Hands

The [`XrControllers`](https://developer.playcanvas.com/user-manual/xr/controllers.md#controller-models) script draws a model of each tracked hand, and moves the model's bones with the joints.

To draw hands your own way, create the shapes for a hand when it's added, and move them to the joints every frame. This draws a sphere at each joint:

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

app.xr.input.on('add', (inputSource) => {
    if (!inputSource.hand) return;

    // A sphere for each joint
    const spheres = inputSource.hand.joints.map(() => {
        const sphere = new Entity();
        sphere.addComponent('render', { type: 'sphere' });
        app.root.addChild(sphere);
        return sphere;
    });
    hands.set(inputSource, spheres);

    inputSource.once('remove', () => {
        for (const sphere of spheres) {
            sphere.destroy();
        }
        hands.delete(inputSource);
    });
});

app.on('update', () => {
    for (const [inputSource, spheres] of hands) {
        const { joints, tracking } = inputSource.hand;
        joints.forEach((joint, i) => {
            const sphere = spheres[i];
            sphere.enabled = tracking;
            sphere.setPosition(joint.getPosition());
            sphere.setRotation(joint.getRotation());

            const size = joint.radius * 2;
            sphere.setLocalScale(size, size, size);
        });
    }
});
```

## Tracking

The device tracks hands with its cameras, so it loses a hand that leaves their view, is hidden behind the other hand, or moves too fast. While a hand isn't tracked, `hand.tracking` is `false`, and its joints keep their last poses. The hand fires `trackinglost` when it loses tracking and `tracking` when it regains it:

```javascript
app.xr.input.on('add', (inputSource) => {
    const hand = inputSource.hand;
    if (!hand) return;

    hand.on('trackinglost', () => {
        console.log(`Lost the ${inputSource.handedness} hand`);
    });
    hand.on('tracking', () => {
        console.log(`Found the ${inputSource.handedness} hand`);
    });
});
```

Hide what you draw for a hand while it isn't tracked, as the example in [Drawing Hands](https://developer.playcanvas.com/user-manual/xr/hand-tracking.md#drawing-hands) does. `XrControllers` hides its hand models too. The input source stays in the list while its hand isn't tracked.

## Gestures

The engine detects two gestures: the pinch, as the select, and the fist, as the squeeze. For others, compare the poses of the joints. This measures how far the thumb is from each fingertip, which detects pinches with any finger:

```javascript
// Whether the thumb touches the tip of a finger, from 1 (index) to 4 (pinky)
const isPinching = (hand, finger) => {
    const thumb = hand.fingers[0].tip.getPosition();
    const tip = hand.fingers[finger].tip.getPosition();
    return thumb.distance(tip) < 0.015;
};
```

And this checks whether the palm faces the user, as when they turn it up to look at it:

```javascript
const palm = new Vec3();
const toHead = new Vec3();

// Whether the palm of a hand faces the camera
const palmFacesUser = (hand, camera) => {
    const wrist = hand.wrist;

    // The wrist joint's negative Y axis points out of the palm
    wrist.getRotation().transformVector(Vec3.DOWN, palm);
    toHead.sub2(camera.getPosition(), wrist.getPosition()).normalize();
    return palm.dot(toHead) > 0.5;
};
```

Tracking is noisy, so require a gesture to change by a margin before it ends. For example, start a pinch at 1.5 cm and end it at 3 cm, so that a pinch near the threshold doesn't flicker on and off. Pressing buttons with a fingertip is in [Pointing and Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md#pressing-with-a-fingertip).

## Designing for Hands

- **Hands have no thumbsticks.** Let users teleport by pinching, as the [`XrNavigation`](https://developer.playcanvas.com/user-manual/xr/locomotion.md) script does, and give them other ways to do what a controller's buttons would.
- **Make targets large.** A tracked hand's ray is less steady than a controller's, so make buttons and other targets larger than for controllers, and keep them within reach.
- **Leave the system gestures alone.** On a Meta Quest, a pinch with the palm facing the user opens the system menu. Don't use it for anything else. `XrNavigation` ignores those pinches.
- **Keep hands low.** Holding hands up in front of the body is tiring, so keep interactions short and close to the body, below the shoulders.
- **Give feedback.** Without buttons to feel, users need to see or hear that a pinch or a press has worked.

## See Also

- [Input Sources](https://developer.playcanvas.com/user-manual/xr/input-sources.md) - Rays, select and squeeze, and handedness
- [Pointing and Grabbing](https://developer.playcanvas.com/user-manual/xr/pointing-and-grabbing.md) - Grabbing objects and pressing buttons with hands and controllers
- [UI in XR](https://developer.playcanvas.com/user-manual/user-interface/xr.md#xr-menus) - The `XrMenu` script's menu on the palm of a hand
- [XrHand](https://api.playcanvas.com/engine/classes/XrHand.html) and [XrJoint](https://api.playcanvas.com/engine/classes/XrJoint.html) - API reference
