# Hit Testing

A hit test casts a ray at the real world, and finds the nearest point where it meets a surface that the device knows about, such as the floor, a wall or a table. The result has a position and a rotation that lies flat on the surface, which makes hit testing the usual way to place content in AR: show the user where something will go, and put it there when they select.

[Video](https://developer.playcanvas.com/video/xr-hit-testing.mp4)

[Live example: AR Hit Test](https://playcanvas.com/examples/#/xr/ar-hit-test) ([source](https://github.com/playcanvas/engine/blob/main/examples/src/examples/xr/ar-hit-test/example.mjs))

## Starting a Hit Test

Every AR session asks for hit testing, so there is nothing to request. `app.xr.hitTest.supported` is `true` when the browser implements it, and `available` is `true` once a session has it. Hit tests run from **hit test sources**. Each one casts its ray every frame, and fires `result` in every frame in which the ray meets a surface. Start a source once the session has started:

```javascript
app.xr.on('start', () => {
    if (!app.xr.hitTest.available) return;

    // Cast a ray straight ahead from the center of the user's view
    app.xr.hitTest.start({
        callback: (err, hitTestSource) => {
            if (err) {
                console.error(`Failed to start a hit test: ${err.message}`);
                return;
            }
            hitTestSource.on('result', (position, rotation) => {
                console.log(`The view meets a surface at ${position}`);
            });
        }
    });
});
```

A source starts asynchronously, and the callback is passed an error or the new [`XrHitTestSource`](https://api.playcanvas.com/engine/classes/XrHitTestSource.html). `hitTestSource.remove()` stops it, and every source stops when the session ends, so start them again in each session's `start` handler.

Hit tests only find what the device has found. A headset such as a Meta Quest 3 senses the room's surfaces as soon as the session starts. A phone finds surfaces in its camera image as the user moves it around, so hit tests return results only after a few seconds of looking around. Until then, ask the user to move their phone slowly over the floor.

## Results

The handler of `result` is passed the nearest hit's position and rotation, the input source the hit belongs to, for [screen taps](https://developer.playcanvas.com/user-manual/xr/ar/hit-testing.md#hit-tests-from-screen-taps), and the browser's [`XRHitTestResult`](https://developer.mozilla.org/docs/Web/API/XRHitTestResult):

- **The pose is in tracking space.** Hit test results are relative to the [rig](https://developer.playcanvas.com/user-manual/xr/sessions.md#the-camera-and-its-rig), as the camera's local pose is. Use them as the local position and rotation of children of the rig. See [Tracking Space](https://developer.playcanvas.com/user-manual/xr/sessions.md#tracking-space).
- **The rotation's Y axis is the surface's normal.** It points up from a floor or a table, and out of a wall into the room, so an object placed with the rotation stands on the surface.
- **The vectors are reused.** The position and rotation are overwritten for the next result, so copy them if you keep them.
- **No hit, no event.** A frame in which the ray meets nothing fires no `result`, so content that follows the results stays where the last one put it.

`app.xr.hitTest` also fires `result` for every source, with the source before the other arguments.

## Showing a Reticle

A reticle, a ring that lies on the surface in the middle of the user's view, shows them where content will go. Make it a child of the rig, move it to each result, and hide it in frames without one. Results come before the application's `update` event in each frame, so `update` can tell whether this frame had one:

```javascript
const reticle = new Entity('reticle');
reticle.addComponent('render', { type: 'torus' });
reticle.setLocalScale(0.2, 0.02, 0.2);
reticle.enabled = false;
rig.addChild(reticle);

let hitThisFrame = false;

app.xr.on('start', () => {
    app.xr.hitTest.start({
        callback: (err, hitTestSource) => {
            if (err) return;
            hitTestSource.on('result', (position, rotation) => {
                reticle.setLocalPosition(position);
                reticle.setLocalRotation(rotation);
                hitThisFrame = true;
            });
        }
    });
});

app.on('update', () => {
    reticle.enabled = app.xr.active && hitThisFrame;
    hitThisFrame = false;
});
```

## Placing Content

Put a copy of something at the reticle when the user selects. On a phone that's a tap anywhere on the screen, and on a headset a pull of the trigger or a pinch:

```javascript
const placeBox = (position, rotation) => {
    const box = new Entity('box');
    box.addComponent('render', { type: 'box' });
    box.setLocalScale(0.2, 0.2, 0.2);
    rig.addChild(box);

    // Stand the box on the surface: up its normal by half its height
    box.setLocalPosition(position);
    box.setLocalRotation(rotation);
    box.translateLocal(0, 0.1, 0);
};

app.xr.input.on('select', () => {
    if (reticle.enabled) {
        placeBox(reticle.getLocalPosition(), reticle.getLocalRotation());
    }
});
```

The device keeps refining its estimate of the room, so content placed at a fixed pose can drift from its spot over a long session. [Anchor](https://developer.playcanvas.com/user-manual/xr/ar/hit-testing.md#anchoring-results) it to stay put.

## Hit Tests from Screen Taps

On a phone, the user can tap where they want something to go, rather than point the center of the screen at it. Each tap is a [transient input source](https://developer.playcanvas.com/user-manual/xr/input-sources.md#kinds-of-input-source) with the profile `'generic-touchscreen'`, which only exists while the finger is down. A hit test source started with that profile casts the ray of every tap, and passes the tap's input source with each result:

```javascript
// The latest hit of each tap that is down
const tapHits = new Map();

app.xr.on('start', () => {
    app.xr.hitTest.start({
        profile: 'generic-touchscreen',
        callback: (err, hitTestSource) => {
            if (err) return;
            hitTestSource.on('result', (position, rotation, inputSource) => {
                tapHits.set(inputSource, {
                    position: position.clone(),
                    rotation: rotation.clone()
                });
            });
        }
    });
});

// Place a box where the tap was when the finger lifts
app.xr.input.on('selectend', (inputSource) => {
    const hit = tapHits.get(inputSource);
    tapHits.delete(inputSource);
    if (hit) {
        placeBox(hit.position, hit.rotation);
    }
});
```

The browser starts to report results for a tap a moment after the finger touches down, so there are none yet when the tap starts. That's why this places the box when the tap ends. A very quick tap can end before any arrive, and places nothing.

`inputSource.hitTestStart()` starts a source with the input source's own profile, for its results alone, and the input source fires `hittest:result` with each one. Like the profile option, it uses WebXR's hit tests for transient input, which the WebXR specification only gives for transient input sources, such as taps. Some browsers also give them for controllers and hands, but don't rely on it. To find where a controller or a hand points in the room, test its ray against [detected planes](https://developer.playcanvas.com/user-manual/xr/ar/plane-detection.md) or [meshes](https://developer.playcanvas.com/user-manual/xr/ar/mesh-detection.md), or start a hit test source for its target ray space through [WebXR directly](https://developer.playcanvas.com/user-manual/xr/sessions.md#using-webxr-directly).

## Other Rays

A source's ray starts at the origin of a reference space, and points along its negative Z axis. The default space is the viewer's, `XRSPACE_VIEWER`, which moves with the user's head. Set `offsetRay` to cast a different ray in the space, such as one that points down at the floor in front of the user:

```javascript
// From the user's head, 45 degrees below the direction they face
const ray = new Ray(new Vec3(0, 0, 0), new Vec3(0, -1, -1).normalize());

app.xr.hitTest.start({
    spaceType: XRSPACE_VIEWER,
    offsetRay: ray,
    callback: (err, hitTestSource) => {
        if (err) return;
        hitTestSource.on('result', (position) => {
            console.log(`The ground ahead is at ${position}`);
        });
    }
});
```

A source's ray can't change once it has started. To cast a ray that is fixed in the room, start a source in the session's reference space, such as `XRSPACE_LOCALFLOOR`, with an `offsetRay` in tracking space.

`entityTypes` chooses what the ray can hit, as an array of types: `XRTRACKABLE_PLANE` for planes, which is the default, `XRTRACKABLE_POINT` for the feature points that a phone tracks, and `XRTRACKABLE_MESH` for meshes. Browsers support it unevenly. Chrome only uses it behind an experimental flag, and a browser that doesn't know a type fails to start the source, so leave it out unless you have tested it on the devices you target.

## Anchoring Results

An [anchor](https://developer.playcanvas.com/user-manual/xr/ar/anchors.md) created from a hit test result is attached to the surface that the hit test found, and follows it as the device refines the room, so content on the anchor stays put. A result can only be anchored in the frame it belongs to, so create the anchor in the `result` handler, as [Creating Anchors](https://developer.playcanvas.com/user-manual/xr/ar/anchors.md#creating-anchors) shows. Request anchors when you start the session.

## See Also

- [Anchors](https://developer.playcanvas.com/user-manual/xr/ar/anchors.md) - Keeping placed content in place
- [Plane Detection](https://developer.playcanvas.com/user-manual/xr/ar/plane-detection.md) - The surfaces that hit tests find, with their outlines and labels
- [WebXR AR: Hit Test](https://developer.playcanvas.com/tutorials/webxr-ar-hit-test/) - A tutorial that builds hit testing in the Editor
- [XrHitTest](https://api.playcanvas.com/engine/classes/XrHitTest.html) and [XrHitTestSource](https://api.playcanvas.com/engine/classes/XrHitTestSource.html) - API reference
