# Anchors

An anchor is a place in the real world that the device keeps track of. As a session goes on, the device learns more about the room and corrects its estimate of where things are, so content placed at a fixed position can drift away from the real spot it was put on. An anchor moves with the correction and stays on its spot, and content that follows the anchor stays where the user put it. On some devices, anchors also last from one session to the next.

[Live example: AR Anchors Persistence](https://playcanvas.com/examples/#/xr/ar-anchors-persistence) ([source](https://github.com/playcanvas/engine/blob/main/examples/src/examples/xr/ar-anchors-persistence/example.mjs))

## Requesting Anchors

Ask for anchors when you start an AR session:

```javascript
camera.camera.startXr(XRTYPE_AR, XRSPACE_LOCALFLOOR, {
    anchors: true
});

app.xr.on('start', () => {
    if (!app.xr.anchors.available) {
        console.log('This session has no anchors');
    }
});
```

`app.xr.anchors.supported` is `true` when the browser implements anchors. `available` becomes `true`, and `app.xr.anchors` fires `available`, when a session that has them starts.

## Creating Anchors

The best place for an anchor is on a surface that a [hit test](https://developer.playcanvas.com/user-manual/xr/ar/hit-testing.md) found. Create it from the hit test result, and it's attached to that surface, so it follows the surface as the device refines it. A hit test result can only be anchored in the frame that it belongs to, so create the anchor in the result handler. This anchors the next result after each select, and puts a cone on each anchor:

```javascript
let anchorNext = false;
app.xr.input.on('select', () => {
    anchorNext = true;
});

// The result handler of a hit test source, such as one that casts from the viewer
hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => {
    if (!anchorNext) return;
    anchorNext = false;

    app.xr.anchors.create(hitTestResult, (err, anchor) => {
        if (err) {
            console.error(`Failed to create an anchor: ${err.message}`);
            return;
        }
        followAnchor(anchor);
    });
});
```

`followAnchor()` is below. Anchors are created asynchronously, and the callback is passed an error or the new anchor. `app.xr.anchors` also fires `add` for each new anchor.

You can also create an anchor at any position and rotation in [tracking space](https://developer.playcanvas.com/user-manual/xr/sessions.md#tracking-space), such as where the user has dragged an object to, with `app.xr.anchors.create(position, rotation, callback)`. An anchor that isn't on a detected surface can only stay as close to its spot as the device's tracking of the room allows.

:::note

In engine 2.24, an anchor created from a hit test result, or [restored](https://developer.playcanvas.com/user-manual/xr/ar/anchors.md#persistence), is added twice: `add` fires for two [`XrAnchor`](https://api.playcanvas.com/engine/classes/XrAnchor.html) objects on the same spot, and only the one passed to the callback has the anchor's `uuid`. So follow these anchors from their callbacks, as this page does, rather than from `add`. For `create(position, rotation)`, it's the other way around: its callback is only called if creating the anchor fails, so only `add` reports the new anchor, with its pose already set.

:::

## Following an Anchor

An anchor's `getPosition()` and `getRotation()` return its pose in tracking space, and it fires `change` when the pose changes. Keep an object on the anchor by making it a child of the [rig](https://developer.playcanvas.com/user-manual/xr/sessions.md#the-camera-and-its-rig), and setting its local position and rotation:

```javascript
const followAnchor = (anchor) => {
    const cone = new Entity('cone');
    cone.addComponent('render', { type: 'cone' });
    cone.setLocalScale(0.1, 0.1, 0.1);
    // Hidden until the anchor has a pose
    cone.enabled = false;
    rig.addChild(cone);

    anchor.on('change', () => {
        cone.setLocalPosition(anchor.getPosition());
        cone.setLocalRotation(anchor.getRotation());
        // Stand the cone on the anchor, along the anchor's Y axis
        cone.translateLocal(0, 0.05, 0);
        cone.enabled = true;
    });

    anchor.once('destroy', () => {
        cone.destroy();
    });
};
```

An anchor created from a hit test result, or restored, gets its pose in the frame after it's created, with its first `change`. Until then, its position is the origin of tracking space, which is why the cone stays hidden until the anchor changes.

`app.xr.anchors.list` lists the session's anchors. `anchor.destroy()` deletes an anchor, and fires its `destroy` event. The device can also lose an anchor it can no longer track, and every anchor is destroyed when the session ends, so remove what follows an anchor in its `destroy` handler, as above.

## Persistence

An anchor can outlive its session on devices that support it, such as the Meta Quest: see [Platforms](https://developer.playcanvas.com/user-manual/xr/platforms.md#ar-features). `app.xr.anchors.persistence` is `true` when the browser supports it. `anchor.persist()` gives an anchor an identifier, a UUID, that a later session can restore it with:

```javascript
anchor.persist((err, uuid) => {
    if (err) {
        console.error(`Failed to persist an anchor: ${err.message}`);
        return;
    }
    // Remember what the anchor holds, to put it back in a later session
    const saved = JSON.parse(localStorage.getItem('anchors') ?? '{}');
    saved[uuid] = 'cone';
    localStorage.setItem('anchors', JSON.stringify(saved));
});
```

The device remembers the identifiers of the anchors that your site persists. During a session, `app.xr.anchors.uuids` lists them, and `app.xr.anchors.restore()` recreates an anchor from its identifier:

```javascript
app.xr.on('start', () => {
    // uuids is null in a session without anchors, or on a device without persistence
    const saved = JSON.parse(localStorage.getItem('anchors') ?? '{}');
    for (const uuid of app.xr.anchors.uuids ?? []) {
        if (!saved[uuid]) continue;

        app.xr.anchors.restore(uuid, (err, anchor) => {
            if (err) {
                console.error(`Failed to restore an anchor: ${err.message}`);
                return;
            }
            followAnchor(anchor);
        });
    }
});
```

A restored anchor has its identifier in `uuid`, and `persistent` is `true`. To stop restoring an anchor, call `anchor.forget()`, or `app.xr.anchors.forget(uuid)` for one that isn't restored. Forget the anchors that the user removes, as devices limit how many a site can keep: a Meta Quest keeps 8 for each site, and none in private browsing. A device also deletes them when the user clears the site's data, so treat `restore()` failing as normal.

## See Also

- [Hit Testing](https://developer.playcanvas.com/user-manual/xr/ar/hit-testing.md) - Finding the surfaces to anchor content to
- [XrAnchors](https://api.playcanvas.com/engine/classes/XrAnchors.html) and [XrAnchor](https://api.playcanvas.com/engine/classes/XrAnchor.html) - API reference
