Skip to content

Device and haptics

Updated

The same scene can run on a desktop browser, a phone, a tablet or a headset. Four small globals help a script make the most of whichever one it is on. Device answers questions about the platform, so a script can adapt its controls or layout. Haptics makes the player feel something: a rumble in an XR controller, a gamepad or a phone. Torch lights the lamp beside a phone’s back camera. WebBrowser reads the page’s address and its query parameters, and opens links.

You should know:

  • How async hooks and promises work in a script; see Scripting.
  • For XR checks, what an immersive session is; see XR.

Device is a set of functions. Most return at once; two return promises.

Member What it returns
operatingSystem() 'Windows', 'macOS', 'Linux', 'Android', 'iOS' or 'Unknown'. An iPad asking for desktop sites still reads as 'iOS'.
isMobile() Whether it is Android or iOS.
isTouch() Whether the device has a touch screen, touch laptops included.
isHeadset() Whether this is a headset’s own browser (Meta Quest, Pico, Wolvic, HTC Vive, Apple Vision Pro).
hasWebXR() Whether the browser has the WebXR API. Desktop browsers have it too, so this does not mean a headset is present.
supportsImmersiveVR() A promise of whether an immersive VR session is possible here.
isXRPresenting() Whether the scene is being rendered into a headset right now. This is the one to branch layout on.
batteryStatus() A promise of { level, charging, chargingTime, dischargingTime }: level from 0 to 100, times in seconds or Infinity. null where the browser does not report the battery.
screenSize() The display’s { width, height } in CSS pixels, and its pixelRatio.

Haptics.vibrate(pattern, options?) vibrates whatever the player has: the XR controllers during a session, a connected gamepad otherwise, or the phone.

Argument What it is
pattern A duration in milliseconds, or a list of alternating vibrate and pause durations: [100, 50, 100] buzzes, pauses, buzzes.
options.intensity 0 to 1, default 1. A phone has a single strength and ignores it.
options.hand In XR, 'left', 'right' or 'both' (default).

It returns true when a device took the vibration and false otherwise: on a desktop without a gamepad, on iPhone and iPad (which cannot vibrate from a web page), and on a phone the player has not yet tapped.

Haptics.cancel() stops every vibration, patterns included.

Torch lights the lamp beside a phone’s back camera. Browsers only light it through that camera’s stream, so turning it on starts the back camera, asking camera permission the first time. It cannot be on while the front camera streams. Phones with a usable torch are mostly Android phones in Chrome; elsewhere on() resolves false.

Member What it does
on() A promise: true once lit, false without a torch or a usable camera.
off() Put it out, unless another script still wants it on. Returns a promise.
toggle() A promise of whether it is now on.
isOn() Whether it is lit.
isSupported() Whether the browser knows the torch setting at all. on() gives the final answer.

The torch stays lit while any script wants it on. A script’s torch goes off when the script is released.

Member What it returns
url() The page’s full URL.
hostname() The page’s host name.
queryParams() The query string as an object. Numbers and true/false are converted, empty values are null, and name[] keys collect into an array.
navigateToURL(url) Open url in a new tab. Only http:, https:, mailto: and tel: links are allowed; anything else is refused and logged.
PlatformSetup.jx
#pragma lifecycle(startup, update)
let desktopHelp;
let touchHelp;
let xrHelp;
let wasPresenting = null;
function startup() {
desktopHelp = findEntity('Keyboard Help');
touchHelp = findEntity('Touch Help');
xrHelp = findEntity('XR Help');
log(`Running on ${Device.operatingSystem()}, ${Device.isMobile() ? 'mobile' : 'desktop'}`);
if (Device.isHeadset()) log('Headset browser detected');
}
function update() {
const presenting = Device.isXRPresenting();
if (presenting === wasPresenting) return;
wasPresenting = presenting;
xrHelp.setEnabled(presenting);
touchHelp.setEnabled(!presenting && Device.isTouch());
desktopHelp.setEnabled(!presenting && !Device.isTouch());
}
  • startup finds the three help panels once and logs what kind of device this is.
  • update checks isXRPresenting() every frame, because the player can enter or leave VR at any time. The wasPresenting comparison means the panels are switched only when the state changes.
  • setEnabled shows or hides a whole entity with its children. The touch panel is shown on touch screens, the keyboard panel elsewhere, and only the XR panel in a headset session.
GrabRumble.jx
#pragma lifecycle(startup)
function startup() {
// Every crate has a Grabbable and a Signal Emitter with the signal 'crates'.
on('crates', (event) => {
if (event.eventType === EventType.Grabbable.Hover) {
Haptics.vibrate(15, { intensity: 0.3 });
}
if (event.eventType === EventType.Grabbable.Start) {
Haptics.vibrate(60, { intensity: 0.8 });
}
if (event.eventType === EventType.Grabbable.End) {
// A double tick on release; flash the crate where vibration is impossible.
if (!Haptics.vibrate([30, 40, 30], { intensity: 0.5 })) emit('ui/flash', { id: event.entityId });
}
});
}
  • One listener handles every crate, because they all share the signal crates. event.entityId says which crate sent the event.
  • A light, short buzz on hover, a stronger one on grab, and a two-pulse pattern on release give three distinct feelings.
  • vibrate returns false where nothing can vibrate, such as a desktop with no gamepad. The script then falls back to a visual cue.
  • In XR, without hand, both controllers vibrate. To vibrate only the hand that grabbed, you would track which controller is pressed; see XR controllers and hands.
TorchButton.jx
#pragma lifecycle(startup)
function startup() {
const label = findEntity('Torch Label').getComponent(UILabelComponent);
if (!Torch.isSupported()) label.setProps({ text: 'No torch on this device' });
// A UI button sends its presses on 'ui/torch'.
on('ui/torch', async (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
const lit = await Torch.toggle();
label.setProps({ text: lit ? 'Torch: on' : 'Torch: off' });
});
}
  • isSupported() is a quick first check; the real answer comes when the torch is asked to turn on.
  • toggle() returns a promise of the new state, so the listener is async and awaits it. The first time, the browser asks for camera permission.
  • The torch goes off on its own when the script is released, so there is nothing to clean up.

3. Start from the URL, and a battery saver

Section titled “3. Start from the URL, and a battery saver”
LaunchOptions.jx
#pragma lifecycle(startup)
async function startup() {
const params = WebBrowser.queryParams();
log('Opened from', WebBrowser.hostname(), 'with', params);
// ?level=forest loads that scene; ?debug=true shows the stats panel.
if (typeof params.level === 'string') await Scenes.load(params.level);
findEntity('Stats Panel')?.setEnabled(params.debug === true);
// On a low battery, switch off the heaviest decoration.
const battery = await Device.batteryStatus();
if (battery && !battery.charging && battery.level < 20) {
findEntity('Particle Rain')?.setEnabled(false);
log(`Battery at ${battery.level}%: effects reduced`);
}
// A UI button sends its presses on 'ui/help'.
on('ui/help', (event) => {
if (event.eventType === EventType.UIButton.Press) WebBrowser.navigateToURL('https://example.com/help');
});
}
  • queryParams() turns ?level=forest&debug=true into { level: 'forest', debug: true }: true arrives as a boolean, not a string.
  • Scenes.load switches to the named scene and returns a promise, awaited inside the async startup.
  • batteryStatus() resolves to null where the browser does not report the battery, so the script checks it before reading level.
  • navigateToURL opens the help page in a new tab, from a button press.
  • Using hasWebXR() to detect a headset. Desktop browsers have WebXR too. Use isHeadset() for the browser, isXRPresenting() for an active session.
  • Expecting vibration on iPhone. iPhones and iPads cannot vibrate from a web page; vibrate returns false. Always have a fallback.
  • Vibrating a phone before the first tap. Phone browsers only vibrate once the player has interacted with the page.
  • Turning on the torch while the front camera streams. The torch needs the back camera. Stop a front-camera stream first.
  • Treating query values as strings. queryParams() converts numbers and booleans. ?count=3 gives the number 3.
  • Opening arbitrary links. navigateToURL refuses schemes other than http:, https:, mailto: and tel:.