Skip to content

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.

You should know:

  • How to poll devices in update, and what async hooks are; see Scripting.
  • How a UI button sends a signal to a script, since some browsers only grant sensors after a tap; see UI.

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() resolves true at once without a prompt.
  • Location asks permission the first time a script calls start(), and works only on secure (https) pages.
  • Readings are null until they arrive. A desktop without sensors, or an iPhone before permission, reports null and available stays false. 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.

Input.accelerometer reads the device’s motion.

Member What it returns
available Whether a reading has arrived.
requestPermission() 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.
accelerationIncludingGravity() { 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.
rotationRate() { alpha, beta, gamma }, how fast the device turns, in degrees per second. null before the first reading.

Input.gyroscope reads the device’s orientation.

Member What it returns
available Whether a reading has arrived.
requestPermission() 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.Quaternion 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.

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.

A board tilts with the phone, or with the arrow keys where no motion reading arrives, such as on a desktop.

TiltBoard.jx
#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);
}
  • accelerationIncludingGravity() is null without 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 -1 to 1, 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.
TiltMarble.jx
#pragma lifecycle(startup, update)
const PUSH = 0.4; // force per m/s² of tilt
let 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 is async so it can await the answer.
  • accelerationIncludingGravity() includes the pull of gravity, so its x and y grow as the phone tilts. It is null until a reading arrives, so the script waits.
  • The tilt becomes a force on the marble’s rigid body. A force added with addForce keeps applying on every physics step until it is reset, so the script calls resetForces() first and replaces last frame’s force with this frame’s. Forces and rigid bodies are covered in Physics.
MagicWindow.jx
#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);
}
  • camera is the script global for the camera the player sees through; it is undefined until 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.
ShakeDetector.jx
#pragma lifecycle(update)
const THRESHOLD = 18; // m/s² of movement that counts as a shake
const COOLDOWN = 1; // seconds between two shakes
let 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.hypot combines the three axes into one strength.
  • The cooldown stops one vigorous shake from firing many times in a row.
TreasureHunt.jx
#pragma lifecycle(startup, update, dispose)
const TREASURE = { latitude: 48.8584, longitude: 2.2945 };
const RADIUS = 25; // metres
let 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();
}
  • startup is async so it can await Input.location.start(), which asks permission and resolves once the first position arrives.
  • distance measures metres over the earth’s surface between the player and the treasure.
  • Adding accuracy to 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. dispose also stops it if the script goes away first.
  • Asking permission outside a tap. On iPhone and iPad, requestPermission() called from startup or update is refused. Call it from a button press.
  • Treating null as zero. Readings are null until they arrive. Always check before using them.
  • Forgetting to stop location. GPS drains the battery. Call stop() when done.
  • Mixing up acceleration() and accelerationIncludingGravity(). Use the first for movement (shakes, jolts) and the second for tilt.
  • Expecting sensors on a desktop. Most desktops and laptops have none: available stays false. Offer another control, such as the keyboard.