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.
Before you start
Section titled “Before you start”- 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.
What Input.xr offers
Section titled “What Input.xr offers”| Member | What it gives | Read |
|---|---|---|
Input. |
How many XR inputs there are: controllers, tracked hands, and screen taps in AR; 0 outside XR. |
XR controllers and hands |
Input. |
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. |
The passthrough camera’s image. | The passthrough camera |
Input. |
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.
The viewer
Section titled “The viewer”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.. |
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.
The passthrough camera
Section titled “The passthrough camera”On devices that stream their cameras to the browser, a script can read the real image the player sees.
| Member | What it gives |
|---|---|
Input. |
Whether there is a camera image here. |
Input. |
Why not, as text, or null when it is available. |
Input. |
The live image as a texture, to show on a mesh; null while there is none. |
Input. |
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. |
A promise of an encoded photo, like Input.: 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
poseandprojection. - 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;
poseis the head’s. - Elsewhere there is no camera image, and
available()isfalse. - Read it in a frame, from
update,startupor 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.
The room’s light
Section titled “The room’s light”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.
Body tracking
Section titled “Body tracking”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.
Session features
Section titled “Session features”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. |
light estimation |
A script reading Input. |
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.
Device checks
Section titled “Device checks”The Device global answers questions about the platform, so a script can adapt.
| Member | What it returns |
|---|---|
Device. |
Whether the runtime is rendering into a headset right now. Use it to switch layouts. |
Device. |
Whether the browser has WebXR at all. Desktop browsers often do. |
Device. |
A promise of whether an immersive VR session is possible here. |
Device. |
Whether this is a headset’s own browser. |
See Device and haptics for every member, and Haptics for vibrating the controllers.
Rays into the real room
Section titled “Rays into the real room”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.
Examples
Section titled “Examples”1. Adapt the layout to a headset
Section titled “1. Adapt the layout to a headset”A flat menu is shown on screens and hidden in a headset, where a world-space menu takes over.
#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);}A flat menu pinned to the screen on laptops and phones, swapped for a world-space menu while a headset is presenting: Device.isXRPresenting() checked by a Behavior script that enables one menu or the other.
In this browser preview the flat menu shows at the top left and the world menu stays hidden. In a headset session the world menu would take over. Drag to orbit the camera, scroll to zoom.
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.
Snippets
Section titled “Snippets”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.
#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.poseis read every frame;trackedis false outside a session, so on a desktop the panel stays where it was placed.goalis 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.lookAtturns the panel towards the player.
2. Select by looking
Section titled “2. Select by looking”Looking at an object for one and a half seconds selects it, a common hands-free control.
#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.
dtis the time since the last frame; adding it up measures how long the gaze has rested on one entity.- Setting
heldto-Infinityafter firing prevents repeats until the player looks elsewhere.
3. Tint a virtual lamp like the room
Section titled “3. Tint a virtual lamp like the room”On an AR phone, a virtual lamp’s shade takes the colour of the room’s main light.
#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()isnulluntil there is an estimate, and on devices that do not estimate light.coloris aTHREE.Color;getHexString()turns it into the#rrggbbform a material’scolorprop 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.
#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()isfalseoutside 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.cameraout in the script makes the session ask for camera access.
5. Take a photo of the real room
Section titled “5. Take a photo of the real room”A UI button takes a passthrough photo and sends it to a server.
#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 canawaitthe photo and the upload. unavailable()explains why there is no image, which helps when testing on different devices.captureencodes the current frame as a JPEG no larger than 1024 pixels on its longer side.photo.blobandphoto.fileNamego straight into a form for upload. The photo also carriesposeandrayAt, to find what a pixel shows in the world.
Common mistakes
Section titled “Common mistakes”- 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. WriteInput.xr.camera,Input.xr.light(andInput.xr.bodyin 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,startupor 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
nullandavailable() === false. - Testing
Device.hasWebXR()to decide the layout. Desktop browsers have WebXR too. UseDevice.isXRPresenting().