Skip to content

XR anchors

Updated

A headset or an AR phone keeps track of the room as you move, but its idea of the room drifts a little over time. Content placed by coordinates drifts with it: a virtual vase put on a real table slowly slides off. An anchor fixes that. It is a real spot the device tracks on its own and corrects as it learns more about the room. The XR Anchor component ties an entity to such a spot, so the vase stays on the table. This page covers placing content with hit tests, the XR Anchor’s props, methods and events, and anchors that persist from one session to the next.

  • Read the XR overview for the ideas of session and hit test.
  • You know how to read XR controller buttons. See XR controllers and hands.
  • Anchors work only in play, in an immersive session. Outside a session they hold nothing.

To put something on a real surface you first need to find one. XRRaycaster asks the device where a ray meets the real floor, walls, tables and whatever else it understands. This is a hit test.

Factory The ray
XRRaycaster.fromViewer() Straight ahead of the headset, or of the phone’s camera: ideal for a reticle.
XRRaycaster.fromController(controller) Along a controller or hand ray; null while it is not there.
XRRaycaster.fromScreen() Through the finger touching an AR phone’s screen; hits nothing while no finger touches.

hit({ maxDistance? }) returns the nearest hit or null; hits({ maxDistance? }) every hit, nearest first. Each hit has:

Field What it is
point Where, in the world.
normal Which way the real surface faces there.
orientation A rotation standing on the surface, its up along normal: copy it onto an object to set it down.
distance How far from the controller, or from the head for the viewer and screen rays.
result The device’s own result, which anchorAt uses.
  • The device answers once per frame, and a ray’s first question starts the answering: results come from the next frames. Ask every frame, as a reticle does.
  • Nothing is hit outside a session, in the editor, or on a device that cannot hit-test.

See Picking and raycasts for the other raycasters.

The XR Anchor (comp-xr-anchor) is offered on groups, meshes and primitives.

  • With auto, it anchors the entity where it is when a session starts.
  • anchorAt(hit) anchors it on an XRRaycaster hit: the entity moves there, standing on the surface, and stays tied to it.
  • anchorHere() anchors it where it is now.
  • release() lets go.
  • While tracked, the anchor drives the entity’s world position and rotation. Its scale stays its own.
  • When tracking is lost, the entity stays where it was.
  • When the session ends, the anchor is deleted and the entity keeps its last pose.
Prop Type Default Description
auto boolean true Anchor where the entity is when a session starts.
persistent boolean false Keep the anchor on this device across sessions: next time it comes back where it was.
Member Description
anchorAt(hit) Anchor on an XRRaycaster hit, moving the entity there. Returns false outside a session.
anchorHere() Anchor where the entity is now. Returns false outside a session.
release() Let go of the anchor and any request on its way. The entity keeps its pose.
forget() Stop keeping a persistent anchor across sessions. This session’s anchor stays.
isTracked Whether the device tracks the anchor now.

With a Signal Emitter on the anchored entity:

eventType Constant data When
XRAnchor::tracked EventType.XRAnchor.Tracked {} The device found the anchor, and it drives the entity.
XRAnchor::lost EventType.XRAnchor.Lost {} The device lost it. The entity stays where it was.
XRAnchor::restored EventType.XRAnchor.Restored {} A persistent anchor came back from an earlier session.

With persistent on, the device keeps the anchor across sessions where it supports it (Meta Quest headsets, for example). The next session restores it before anything else and sends XRAnchor::restored.

  • It is meant for entities saved in the scene. A spawned copy has a new id each time, so it cannot find its old anchor.
  • Where anchors do not persist, or browser storage is blocked, it behaves as a plain anchor.
  • If the device lost what it kept, the anchor starts over, as auto says.
  • forget() lets the device forget it.

Using an XR Anchor makes the session ask the device for its anchors feature when the player enters VR or AR. See XR input for session features.

  1. Create the content to place, for example a Chair, with an XR Anchor whose auto is off. Switch the entity off: it is the original the script copies.
  2. Create a Reticle: a thin ring that shows where the content would go.
  3. Every frame, cast XRRaycaster.fromViewer() and move the reticle to the hit, using hit.point and hit.orientation.
  4. When the player confirms, spawn a copy at hit.point and call anchorAt(hit) on its XR Anchor.

On an AR phone, the player touches the floor and lifts the finger to drop a plant there.

TapToPlace.jx
#pragma lifecycle(startup, update)
let screen;
let lastHit = null;
function startup() {
screen = Input.xr.controller(0);
}
function update() {
const hit = XRRaycaster.fromScreen().hit({ maxDistance: 5 });
if (hit) lastHit = hit;
if (!screen.isReleased(XRButton.Trigger) || !lastHit) return;
const plant = spawn('Plant', { position: lastHit.point, enabled: true });
plant.getComponent(XRAnchorComponent).anchorAt(lastHit);
lastHit = null;
}
  • On an AR phone, a finger on the screen counts as an XR input, so Input.xr.controller(0) reads it, and lifting the finger releases the trigger.
  • XRRaycaster.fromScreen() casts through the finger every frame while it touches. Results arrive from the next frames, so the script keeps the latest hit in lastHit rather than asking only at the moment of release.
  • maxDistance: 5 ignores surfaces more than five metres away.
  • anchorAt(lastHit) moves the copy onto the surface, standing on it, and ties it there. lastHit is cleared so the next tap starts fresh.

The reticle follows the gaze every frame; the right trigger places a lamp at the latest valid hit.

ReticlePlace.jx
#pragma lifecycle(startup, update)
let reticle;
let right;
let lastHit = null;
// 'Reticle' is a flat ring mesh. 'Lamp' is a disabled entity with an XR Anchor (auto off).
function startup() {
reticle = findEntity('Reticle');
right = Input.xr.controller('right');
}
function update() {
lastHit = XRRaycaster.fromViewer().hit();
reticle.visible = Boolean(lastHit);
if (!lastHit) return;
reticle.position.copy(lastHit.point);
reticle.quaternion.copy(lastHit.orientation);
if (right.isReleased(XRButton.Trigger)) {
const lamp = spawn('Lamp', { position: lastHit.point, enabled: true });
if (!lamp.getComponent(XRAnchorComponent).anchorAt(lastHit)) log('Not in a session');
}
}
  • Asking fromViewer() every frame keeps the device answering, so a fresh hit is ready whenever the trigger is pulled.
  • The reticle hides when there is no surface ahead, and lies flat on whatever surface there is, thanks to hit.orientation.
  • anchorAt returns false outside a session; the script logs it rather than leaving an unanchored lamp unexplained.

A virtual whiteboard is moved by the player with a Grabbable. When they let go, it is anchored where it was dropped.

AnchorOnDrop.jx
#pragma lifecycle(startup)
// The Whiteboard has a Grabbable, an XR Anchor (auto off) and a Signal Emitter with the signal 'board'.
function startup() {
const board = findEntity('Whiteboard');
const anchor = board.getComponent(XRAnchorComponent);
on('board', (event) => {
if (event.eventType === EventType.Grabbable.Start) anchor.release();
if (event.eventType === EventType.Grabbable.End) anchor.anchorHere();
});
}
  • While the board is held, the anchor must not drive it, so release() lets go as soon as the grab starts.
  • When the grab ends, anchorHere() ties the board to wherever it now is.
  • Both the Grabbable’s events and the XR Anchor’s events would arrive on the same Signal Emitter; the eventType check picks the right ones. See Selection and grabbing.

When the device loses an anchor, the entity freezes where it was, which can look wrong. This script fades it out until tracking returns.

HideWhenLost.jx
#pragma lifecycle(startup)
// On an anchored Statue with a Signal Emitter whose signal is 'statue'.
function startup() {
const statue = self;
on('statue', (event) => {
if (event.entityId !== statue.entityId) return;
if (event.eventType === EventType.XRAnchor.Lost) {
Tween.to(statue.scale, { x: 0.001, y: 0.001, z: 0.001 }, { duration: 0.3 });
}
if (event.eventType === EventType.XRAnchor.Tracked) {
Tween.to(statue.scale, { x: 1, y: 1, z: 1 }, { duration: 0.3 });
}
});
}
  • XRAnchor::lost arrives when the device can no longer see the anchored spot; XRAnchor::tracked when it finds it again.
  • The anchor drives the entity’s position and rotation, never its scale, so shrinking it with a tween is safe.
  • Tween.to animates the scale smoothly over 0.3 seconds.

A museum label is placed once by staff and comes back in the same real place every time.

PersistentLabel.jx
#pragma lifecycle(startup)
// 'Label' is saved in the scene with an XR Anchor: auto off, persistent on,
// and a Signal Emitter with the signal 'label'.
function startup() {
const label = findEntity('Label');
const anchor = label.getComponent(XRAnchorComponent);
on('label', (event) => {
if (event.eventType === EventType.XRAnchor.Restored) log('Label restored from last time');
});
on('staff/place-label', () => {
if (anchor.anchorHere()) log('Label anchored; it will be here next session');
});
on('staff/clear-label', () => {
anchor.forget();
log('The device will forget this placement');
});
}
  • persistent is set on the saved entity, so the anchor is stored under its id and can be found again.
  • At the start of the next session the device restores it and sends XRAnchor::restored.
  • anchorHere() stores a new placement; forget() tells the device to drop the stored one, while this session’s anchor stays.
  • On devices that do not keep anchors, the label simply behaves as a plain anchor.
  • Anchoring a dynamic rigid body. Physics and the anchor fight over the pose. Use a fixed or kinematic body, or none.
  • Asking for a hit only once. Results arrive from the next frames. Cast every frame and use the latest hit.
  • Persistent anchors on spawned copies. A spawned entity has a new id each session, so its stored anchor is never found. Use entities saved in the scene.
  • Expecting anchors on the desktop. anchorAt and anchorHere return false outside a session.
  • Moving an anchored entity by hand. While tracked, the anchor drives its position and rotation. release() first, then anchor again.
  • Leaving auto on for content you place. An auto anchor is created where the entity stands when the session starts. Turn it off for content the script places with anchorAt.