Motion sensors and location
Updated
Phones and tablets know how they are held and where they are. The accelerometer measures how the device moves and which way is down; the gyroscope reports how it is turned; location gives its position on the earth from GPS or the network. With them a scene can roll a marble when the player tilts the phone, turn the camera as the player looks around holding the device, detect a shake, or unlock content when the player reaches a real place. This page covers Input.accelerometer, Input.gyroscope and Input.location.
Before you start
Section titled “Before you start”You should know:
- How to poll devices in
update, and whatasynchooks are; see Scripting. - How a UI button sends a signal to a script, since some browsers only grant sensors after a tap; see UI.
Permissions and availability
Section titled “Permissions and availability”These devices are private, so browsers guard them:
- Motion sensors need permission on iPhone and iPad, and the request must come from a tap or a click. Elsewhere,
requestPermission()resolvestrueat once without a prompt. - Location asks permission the first time a script calls
start(), and works only on secure (https) pages. - Readings are
nulluntil they arrive. A desktop without sensors, or an iPhone before permission, reportsnullandavailablestaysfalse. Nothing reads as “perfectly still” by mistake.
Each reading is a copy of the latest values, so you can keep it without it changing under you.
Accelerometer
Section titled “Accelerometer”Input.accelerometer reads the device’s motion.
| Member | What it returns |
|---|---|
available |
Whether a reading has arrived. |
request |
A promise of whether access is granted. On iPhone and iPad, call it from a tap or a click. |
acceleration() |
{ x, y, z } without gravity, in m/s²: how the device is being moved. null before the first reading. |
acceleration |
{ x, y, z } with gravity: at rest about 9.8 m/s² pointing up, which shows how the device is tilted. null before the first reading. |
rotation |
{ alpha, beta, gamma }, how fast the device turns, in degrees per second. null before the first reading. |
Gyroscope
Section titled “Gyroscope”Input.gyroscope reads the device’s orientation.
| Member | What it returns |
|---|---|
available |
Whether a reading has arrived. |
request |
A promise of whether access is granted. On iPhone and iPad, call it from a tap or a click. |
orientation() |
{ alpha, beta, gamma } in degrees, or null. |
quaternion() |
A new THREE. for a camera looking out of the back of the device, corrected for portrait or landscape: copy it onto a camera. null before the first reading. |
quaternion() is the easiest way to make a “magic window”: the scene’s camera turns exactly as the player turns the phone.
Location
Section titled “Location”Input.location reads where the device is.
| Member | What it does |
|---|---|
start() |
Start watching, asking permission the first time. Resolves true once the first position has arrived; false when permission is refused or the device cannot tell where it is. |
stop() |
Stop watching. The GPS turns off once no script watches. |
isWatching() |
Whether this script is watching. |
position() |
The latest position, the same for every script in a frame; null while not watching or before the first position. |
distance(a, b) |
Metres between two { latitude, longitude } points, over the earth’s surface. |
isSupported() |
Whether this browser can tell where the device is. |
A position has these fields:
| Field | What it is |
|---|---|
latitude, longitude |
Where, in degrees. |
accuracy |
How far off the position may be, in metres. |
altitude |
Metres above sea level, or null when unknown. |
heading |
Direction of travel in degrees clockwise from north, or null when not moving. |
speed |
Metres per second, or null when unknown. |
time |
When it was measured, in milliseconds as Date.now() counts. |
Examples
Section titled “Examples”1. Tilt a board, with a keyboard fallback
Section titled “1. Tilt a board, with a keyboard fallback”A board tilts with the phone, or with the arrow keys where no motion reading arrives, such as on a desktop.
#pragma lifecycle(startup, update)
const MAX_TILT = DEG_TO_RAD(20);let board;let sensor = false;let x = 0;let z = 0;
function startup() { board = findEntity('Board'); log('Arrow keys tilt the board. On a phone, press Motion and tilt it.');
on('ui/motion', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; const granted = await Input.accelerometer.requestPermission(); log(granted ? 'Motion access granted' : 'Motion access refused'); });}
function update(dt) { let wantX = 0; let wantZ = 0; const g = Input.accelerometer.accelerationIncludingGravity(); if (g) { if (!sensor) log('Tilting with the accelerometer'); sensor = true; // Tilting the phone sideways changes x; tilting it forward or back changes y. wantX = THREE.MathUtils.clamp(g.x / 9.8, -1, 1); wantZ = THREE.MathUtils.clamp(-g.y / 9.8, -1, 1); } else { // No reading: a desktop, or a phone before permission. if (Input.keyboard.isKeyPressed(Key.ArrowLeft)) wantX -= 1; if (Input.keyboard.isKeyPressed(Key.ArrowRight)) wantX += 1; if (Input.keyboard.isKeyPressed(Key.ArrowUp)) wantZ -= 1; if (Input.keyboard.isKeyPressed(Key.ArrowDown)) wantZ += 1; } const ease = Math.min(1, dt * 6); x += (wantX - x) * ease; z += (wantZ - z) * ease; board.rotation.set(z * MAX_TILT, 0, -x * MAX_TILT);}A board tilts with the phone through Input.accelerometer; on a desktop, where no reading arrives, the arrow keys tilt it instead.
On a desktop, click the scene and hold the arrow keys. On a phone, press Motion, allow motion access, and tilt the phone. Drag to orbit the camera, scroll to zoom.
accelerationIncludingGravity()isnullwithout a sensor or before permission, which is exactly when the script falls back to the keyboard.- Dividing by 9.8 turns the reading into a tilt from
-1to1, whatever the device. - The board eases toward the wanted tilt with
dt, so sensor noise and key presses both look smooth. - On iPhone and iPad, the Motion button asks permission from a tap, as those devices require.
Snippets
Section titled “Snippets”1. Tilt to roll a marble
Section titled “1. Tilt to roll a marble”#pragma lifecycle(startup, update)
const PUSH = 0.4; // force per m/s² of tiltlet marble;
function startup() { marble = findEntity('Marble').getComponent(PhysicsRigidBodyComponent);
// A UI button's Signal Emitter sends its presses on 'ui/motion'. on('ui/motion', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; const granted = await Input.accelerometer.requestPermission(); log(granted ? 'Tilt control on' : 'Motion access refused'); });}
function update() { const g = Input.accelerometer.accelerationIncludingGravity(); if (!g) return; // no sensor, or no permission yet
// Tilting the phone sideways changes x; tilting it forward or back changes y. marble.resetForces(); marble.addForce({ x: g.x * PUSH, y: 0, z: -g.y * PUSH });}- The button press runs
requestPermission()inside a tap, which iPhone and iPad require. The listener isasyncso it canawaitthe answer. accelerationIncludingGravity()includes the pull of gravity, so itsxandygrow as the phone tilts. It isnulluntil a reading arrives, so the script waits.- The tilt becomes a force on the marble’s rigid body. A force added with
addForcekeeps applying on every physics step until it is reset, so the script callsresetForces()first and replaces last frame’s force with this frame’s. Forces and rigid bodies are covered in Physics.
2. Look around through the phone
Section titled “2. Look around through the phone”#pragma lifecycle(startup, update)
let enabled = false;
function startup() { // A UI button's Signal Emitter sends its presses on 'ui/look'. on('ui/look', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; enabled = await Input.gyroscope.requestPermission(); if (!enabled) log('Gyroscope unavailable or refused'); });}
function update() { if (!enabled || !camera) return; const q = Input.gyroscope.quaternion(); if (q) camera.quaternion.copy(q);}camerais the script global for the camera the player sees through; it isundefineduntil rendering starts, so the script checks it.quaternion()already accounts for how the phone is held, so copying it onto the camera is all it takes.- The camera’s own controller also turns it from touch drags. For a pure gyroscope view, disable the camera controller while this runs; see Cameras.
3. Detect a shake
Section titled “3. Detect a shake”#pragma lifecycle(update)
const THRESHOLD = 18; // m/s² of movement that counts as a shakeconst COOLDOWN = 1; // seconds between two shakeslet wait = 0;
function update(dt) { wait = Math.max(0, wait - dt); const a = Input.accelerometer.acceleration(); if (!a || wait > 0) return;
const strength = Math.hypot(a.x, a.y, a.z); if (strength > THRESHOLD) { wait = COOLDOWN; emit('device/shake', { strength }); log('Shake!', strength.toFixed(1)); }}acceleration()leaves gravity out, so a phone at rest reads close to zero and only real movement counts.Math.hypotcombines the three axes into one strength.- The cooldown stops one vigorous shake from firing many times in a row.
4. A real-world treasure hunt
Section titled “4. A real-world treasure hunt”#pragma lifecycle(startup, update, dispose)
const TREASURE = { latitude: 48.8584, longitude: 2.2945 };const RADIUS = 25; // metreslet watching = false;let found = false;let label;
async function startup() { label = findEntity('Distance Label').getComponent(UILabelComponent); if (!Input.location.isSupported()) { label.setProps({ text: 'Location is not available on this device' }); return; } watching = await Input.location.start(); if (!watching) label.setProps({ text: 'Location permission refused' });}
function update() { if (!watching || found) return; const here = Input.location.position(); if (!here) return;
const metres = Input.location.distance(here, TREASURE); label.setProps({ text: `${Math.round(metres)} m to go (±${Math.round(here.accuracy)} m)` });
if (metres < RADIUS + here.accuracy) { found = true; label.setProps({ text: 'Treasure found!' }); emit('treasure/found'); Input.location.stop(); }}
function dispose() { if (watching) Input.location.stop();}startupisasyncso it canawait Input.location.start(), which asks permission and resolves once the first position arrives.distancemeasures metres over the earth’s surface between the player and the treasure.- Adding
accuracyto the radius accounts for GPS uncertainty, so a player standing on the spot is not told they are still 15 m away. - Once found, the script stops watching to save battery.
disposealso stops it if the script goes away first.
Common mistakes
Section titled “Common mistakes”- Asking permission outside a tap. On iPhone and iPad,
requestPermission()called fromstartuporupdateis refused. Call it from a button press. - Treating
nullas zero. Readings arenulluntil they arrive. Always check before using them. - Forgetting to stop location. GPS drains the battery. Call
stop()when done. - Mixing up
acceleration()andaccelerationIncludingGravity(). Use the first for movement (shakes, jolts) and the second for tilt. - Expecting sensors on a desktop. Most desktops and laptops have none:
availablestaysfalse. Offer another control, such as the keyboard.