Skip to content

XR input

Updated

Input.xr is a script’s window on an immersive session. Besides the controllers and hands, it tells where the player’s head is and where they look, and, on devices that offer them, it gives the live image of the passthrough camera, the room’s light and the tracked body. This page covers those readings, the session features they depend on, and the Device checks that let one script adapt between a laptop, a phone and a headset.

  • Read the XR overview for the ideas of session and session features.
  • Controllers, buttons, thumbsticks, hand joints and gestures are covered in XR controllers and hands. This page does not repeat them.
  • Poll input in update. Every device takes one snapshot per frame, so every script sees the same values in the same frame.
Member What it gives Read
Input.xr.count() How many XR inputs there are: controllers, tracked hands, and screen taps in AR; 0 outside XR. XR controllers and hands
Input.xr.controller(ref) The controller or hand at 'left', 'right' or an index. XR controllers and hands
Input.xr.pose Where the viewer is and looks this frame. The viewer
Input.xr.camera The passthrough camera’s image. The passthrough camera
Input.xr.light() The room’s light this frame. The room’s light
Input.xr.body The tracked body’s joints. Body tracking

Poses are in world space and follow the player rig like the camera, so they stay right after a teleport or a recenter.

Input.xr.pose is where the viewer’s head is this frame. It is never null.

Field What it is
origin The head’s position in the world, a THREE.Vector3.
direction Where the head looks, a unit THREE.Vector3.
orientation How the head is turned, a THREE.Quaternion.
tracked false outside a session or while tracking is lost. The last values are kept.

The pose is updated in place every frame. Copy the values you want to keep, rather than keeping the vectors themselves.

On devices that stream their cameras to the browser, a script can read the real image the player sees.

Member What it gives
Input.xr.camera.available() Whether there is a camera image here.
Input.xr.camera.unavailable() Why not, as text, or null when it is available.
Input.xr.camera.getTexture() The live image as a texture, to show on a mesh; null while there is none.
Input.xr.camera.getRaw({ maxSize? }) A promise of the pixels: data (RGBA bytes, top row first), width, height, and where they were taken from: pose, projection, and rayAt(x, y), the world ray through a pixel.
Input.xr.camera.capture(options?) A promise of an encoded photo, like Input.camera.capture: blob, type, format, fileName, width, height, base64(), plus pose, projection and rayAt.
  • On an AR phone the image is the device’s raw camera image, with the camera’s own pose and projection.
  • On a mixed-reality headset that streams its passthrough camera (Meta Quest 3, for example), the browser asks permission the first time and the camera stays on for the session; pose is the head’s.
  • Elsewhere there is no camera image, and available() is false.
  • Read it in a frame, from update, startup or a signal handler: the image exists only while its frame does.
  • getRaw() reads the pixels back once per call. Ask when you need a frame, not every frame.

Input.xr.light() returns the device’s estimate of the room’s light this frame, or null without an estimate.

Field What it is
direction The world direction towards the main light.
color The main light’s colour, a THREE.Color whose brightest channel is 1.
intensity The main light’s strength.
sh The ambient light all around, as spherical harmonics.

AR on Android phones estimates light; most headsets do not. To simply light the scene like the room, add an XR Light Estimate component instead; see XR world.

Input.xr.body is the tracked body on devices that track it, such as Meta Quest headsets, or null when no body is tracked. body.joint(name) gives { position, orientation } for a joint such as 'hips' or 'left-hand-wrist', or null.

The light estimate and the body joints are updated in place every frame: copy what you keep.

A session’s features are fixed when it starts. When the player enters VR or AR, the runtime looks at the active scene once and asks for what it uses, each as an optional feature, so a device without it still enters.

The scene uses Feature asked for
XR Depth Occlusion depth sensing
XR Light Estimate, or a script calling Input.xr.light( light estimation
A script reading Input.xr.camera camera access
A script reading Input.xr.body body tracking
XR Anchor anchors
  • Only enabled components count. A script is matched by those names written in its code.
  • Hit testing, plane detection, mesh detection and anchors are part of every session’s optional features already.
  • A scene that uses none of these asks for nothing more: no extra permission prompt.

The Device global answers questions about the platform, so a script can adapt.

Member What it returns
Device.isXRPresenting() Whether the runtime is rendering into a headset right now. Use it to switch layouts.
Device.hasWebXR() Whether the browser has WebXR at all. Desktop browsers often do.
Device.supportsImmersiveVR() A promise of whether an immersive VR session is possible here.
Device.isHeadset() Whether this is a headset’s own browser.

See Device and haptics for every member, and Haptics for vibrating the controllers.

XRRaycaster asks the device where a ray meets the real floor, walls and tables: from the viewer (fromViewer()), a controller (fromController(controller)) or a finger on an AR phone’s screen (fromScreen()). It is how content is placed in AR; see XR anchors and Picking and raycasts.

A flat menu is shown on screens and hidden in a headset, where a world-space menu takes over.

LayoutSwitch.jx
#pragma lifecycle(startup, update)
let flatMenu;
let worldMenu;
let inHeadset = null;
function startup() {
flatMenu = findEntity('Flat Menu');
worldMenu = findEntity('World Menu');
}
function update() {
const now = Device.isXRPresenting();
if (now === inHeadset) return;
inHeadset = now;
flatMenu.setEnabled(!now);
worldMenu.setEnabled(now);
}
  • Device.isXRPresenting() is true while the runtime renders into a headset.
  • The menus are switched only when that changes, entering or leaving the session.
  • The same scene works on a laptop, a phone and a headset without separate versions.

1. A panel that floats in front of the player

Section titled “1. A panel that floats in front of the player”

An info panel drifts smoothly to two metres in front of wherever the player looks.

FollowGaze.jx
#pragma lifecycle(update)
const DISTANCE = 2;
const goal = new THREE.Vector3();
function update() {
const viewer = Input.xr.pose;
if (!viewer.tracked) return;
goal.copy(viewer.origin).addScaledVector(viewer.direction, DISTANCE);
self.parent.position.lerp(goal, 0.1);
self.parent.lookAt(viewer.origin);
}
  • Input.xr.pose is read every frame; tracked is false outside a session, so on a desktop the panel stays where it was placed.
  • goal is computed into a reused vector: the head’s position plus two metres along the gaze.
  • lerp(goal, 0.1) moves the panel a tenth of the way each frame, so it follows with a gentle lag instead of being glued to the head.
  • lookAt turns the panel towards the player.

Looking at an object for one and a half seconds selects it, a common hands-free control.

GazeSelect.jx
#pragma lifecycle(update)
const DWELL = 1.5; // seconds
let current = null;
let held = 0;
function update(dt) {
const viewer = Input.xr.pose;
if (!viewer.tracked) return;
const hit = GraphicsRaycaster.fromWorld(viewer.origin, viewer.direction).hit(null, { maxDistance: 10 });
const target = hit && hit.entity;
if (target !== current) {
current = target;
held = 0;
return;
}
if (!current) return;
held += dt;
if (held >= DWELL) {
emit('gaze/select', { id: current.entityId });
held = -Infinity; // fire once until the gaze moves away
}
}
  • GraphicsRaycaster.fromWorld(origin, direction) casts a ray from the head along the gaze, against what is drawn.
  • When the gaze moves to a different entity, the timer restarts.
  • dt is the time since the last frame; adding it up measures how long the gaze has rested on one entity.
  • Setting held to -Infinity after firing prevents repeats until the player looks elsewhere.

On an AR phone, a virtual lamp’s shade takes the colour of the room’s main light.

RoomTint.jx
#pragma lifecycle(startup, update)
let shade;
let lastHex = '';
function startup() {
shade = findEntity('Lamp Shade').getComponent(StandardMaterialComponent);
}
function update() {
const light = Input.xr.light();
if (!light) return;
const hex = `#${light.color.getHexString()}`;
if (hex === lastHex) return;
lastHex = hex;
shade.setProps({ color: hex });
}
  • The text Input.xr.light( in the script makes the session ask for light estimation when the player enters AR.
  • light() is null until there is an estimate, and on devices that do not estimate light.
  • color is a THREE.Color; getHexString() turns it into the #rrggbb form a material’s color prop takes.
  • The material is updated only when the colour changes, not every frame.

4. Show the passthrough on a virtual screen

Section titled “4. Show the passthrough on a virtual screen”

A virtual monitor shows what the device’s camera sees, a “security camera” effect.

PassthroughMonitor.jx
#pragma lifecycle(startup, update)
let screenMesh = null;
function startup() {
screenMesh = new THREE.Mesh(
new THREE.PlaneGeometry(1.6, 0.9),
new THREE.MeshBasicMaterial({ color: 0x222222 }),
);
findEntity('Monitor').add(screenMesh);
}
function update() {
if (!Input.xr.camera.available()) return;
const texture = Input.xr.camera.getTexture();
if (texture && screenMesh.material.map !== texture) {
screenMesh.material.map = texture;
screenMesh.material.color.set(0xffffff);
screenMesh.material.needsUpdate = true;
}
}
  • A plain plane mesh is added to the Monitor entity as its screen, dark until an image exists.
  • available() is false outside a session and on devices without a passthrough image.
  • getTexture() returns the live image as a texture. The script assigns it once; the texture keeps updating by itself.
  • Writing Input.xr.camera out in the script makes the session ask for camera access.

A UI button takes a passthrough photo and sends it to a server.

RoomSnapshot.jx
#pragma lifecycle(startup)
function startup() {
on('ui/snapshot', async () => {
if (!Input.xr.camera.available()) {
log('No camera here:', Input.xr.camera.unavailable());
return;
}
const photo = await Input.xr.camera.capture({ type: 'image/jpeg', maxSize: 1024 });
log('Photo', photo.width, 'x', photo.height);
const form = new FormData();
form.append('file', photo.blob, photo.fileName);
await HttpRequest.post('https://api.example.com/snapshots', { body: form });
});
}
  • The handler is async, so it can await the photo and the upload.
  • unavailable() explains why there is no image, which helps when testing on different devices.
  • capture encodes the current frame as a JPEG no larger than 1024 pixels on its longer side.
  • photo.blob and photo.fileName go straight into a form for upload. The photo also carries pose and rayAt, to find what a pixel shows in the world.
  • Keeping the pose vectors. Input.xr.pose, light() and body joints are updated in place. Copy what you need.
  • Aliasing Input.xr. The session’s features are requested from the literal names in your code. Write Input.xr.camera, Input.xr.light( and Input.xr.body in full.
  • Calling getRaw() every frame. It reads the pixels back each call. Ask only when you need a frame.
  • Reading the camera outside a frame. Read it from update, startup or a signal handler, not from a timer long after.
  • Expecting every device to have everything. Light estimation is mostly on Android phones, body tracking and passthrough mostly on certain headsets. Always handle null and available() === false.
  • Testing Device.hasWebXR() to decide the layout. Desktop browsers have WebXR too. Use Device.isXRPresenting().