# Scenery Scripting -- Guide, features (v0.5.0) One guide per scripting feature, with runnable examples. Sibling bundle (basics -- getting started, events, transforms, materials, feature detection): https://scenery.app/docs/scripting/guide/llms-full.txt Sibling bundles (complete API signatures): engine types https://scenery.app/docs/scripting/api/llms-full.txt, runtime types https://scenery.app/docs/scripting/api/runtime/llms-full.txt Heavier reference pages are fetchable directly: worked examples at https://scenery.app/docs/scripting/guide/examples.md, compute kernels at https://scenery.app/docs/scripting/guide/compute.md, changelog at https://scenery.app/docs/scripting/guide/changelog.md, migration at https://scenery.app/docs/scripting/guide/migration.md. Any docs page is also available as raw markdown by appending `.md` -- e.g. https://scenery.app/docs/scripting/api/mesh.md, https://scenery.app/docs/scripting/guide/examples.md. --- # Gestures & Interactions Gestures come in two layers: - **Object gestures** - drag, rotate, or resize a *specific* object. Enable them on the object, then optionally react in a script. - **Screen gestures** - raw `pan` / `pinch` / `rotate` anywhere on screen, independent of any object. The building block for custom mechanics like flick-to-launch. Screen gestures fire on iPhone, iPad and Mac - not Apple Vision Pro, where input is spatial. Gate a portable script with `environment.features.has('screenGestures')` and fall back to UI controls. See [Feature Detection](/scripting/guide/feature-detection). ## Object gestures Enable a gesture on the descriptor (or in the editor), and the user can manipulate the object directly: ```javascript var crate = await scene.createEntity( createBox(0.2, 0.2, 0.2) .name('crate') .gestures({ drag: true, rotate: true }) ); ``` React to the live manipulation with `on('gesture')` - it fires continuously while the user moves the object. Read `e.phase` (`'began'` / `'changed'` / `'ended'`) and, by kind, `e.translation` / `e.rotation` / `e.scale`: ```javascript crate.on('gesture', function(e) { if (e.phase === 'ended') { console.log('moved by', e.translation.toString()); } }); ``` `doubleTap` and `longPress` are discrete object gestures, available in code: ```javascript crate.on('doubleTap', function() { /* ... */ }); crate.on('longPress', { minimumDuration: 0.5 }, function() { /* ... */ }); ``` ### Release behaviour When a dragged object is let go, `releaseBehavior` decides what happens next: ```javascript createSphere(0.04) .physics({ mode: 'dynamic', mass: 0.2 }) .gestures({ drag: true, releaseBehavior: 'momentum' }); ``` | `releaseBehavior` | On release | | --- | --- | | `'stay'` (default) | Stays where it was let go, then falls under gravity if it has a dynamic body. | | `'reset'` | Animates back to where the gesture started. | | `'momentum'` | Keeps the motion the gesture gave it - a flick throws it, a slow release lets it drift. Tune with `momentumScale` / `angularMomentumScale`. | `'momentum'` gives you a throw with no manual velocity maths - the engine measures the release motion for you. Reach for the scripted approach below only when you need finer control. ## Screen gestures `scene.on('pan' | 'pinch' | 'rotate')` fires for any such gesture anywhere on screen. Read `e.position` (normalized), `e.phase`, and by kind `translation` / `scale` / `rotation` plus `velocity`: ```javascript // Flick strength from a swipe in the bottom of the screen. scene.on('pan', { area: [0, 0.6, 1, 0.4], phase: 'ended' }, function(e) { console.log('flick speed', e.velocity.length()); }); ``` Outside AR (the desktop preview, the Mac app), a one-finger pan **also orbits the camera** by default - so a pan your script reacts to would move your object *and* swing the camera at once. `consume` claims the gesture for your script alone: return `true` from its predicate (evaluated as the gesture begins) and the camera ignores that gesture. Omit `consume` for the smart default, which claims a gesture automatically when it begins on a scene object: ```javascript // Claim the pan only when it starts on the ball; every other pan still orbits the camera. scene.on('pan', { consume: function(e) { return e.hits(ball); } }, function(e) { /* ... */ }); ``` See [scene.on](/scripting/api/scene) for the full payload and `consume` options. ### Swipe the scene to scroll a carousel Pass each scene pan to [`carousel.scrollWith(e)`](/scripting/api/uiview) to scroll the carousel as a swipe on it would. Taps still reach objects, and a pan that began on a draggable object moves only that object. Outside AR, add `consume` so the camera stays still. ## Gestures on panel views Views in a panel on the screen take the same gestures: `view.on('pinch' | 'pan' | 'rotate' | 'tap')`. Positions are in points from the view's top-left corner, and `scale`, `rotation`, `offsetX` and `offsetY` move the view without changing the panel's layout: ```javascript // Drag a card down to close it, or let it spring back. card.on('pan', function(e) { if (e.phase !== 'ended') { card.offsetY = Math.max(0, e.translation.y); return; } if (e.translation.y > e.size.y / 2) { card.isHidden = true; } card.animateTo({ offsetY: 0 }, 0.4, { spring: { bounce: 0.2 } }); }); ``` `view.enablePinchZoom()` covers the common photo case in one line. Panels placed in 3D and Apple Vision Pro don't deliver view gestures; a view inside a carousel takes pinch and rotate but not pan. ## Composing a custom mechanic Specific mechanics - pickup-and-throw, drag-to-aim, swipe-to-navigate - aren't engine features; you compose them in a script from the primitives above plus physics. A flick-to-launch, in miniature: ```javascript var ball = scene.findEntity({ name: 'ball' }); // Claim a pan that starts on the ball; on release, convert its screen velocity to an impulse. scene.on('pan', { consume: function(e) { return e.hits(ball); } }, function(e) { if (e.phase !== 'ended') { return; } var launchScale = 0.002; // screen points/sec -> world impulse; tune for the feel you want var lift = 0.4; // upward component so the throw arcs ball.applyImpulse(new Vector3(e.velocity.x * launchScale, lift, -e.velocity.y * launchScale)); }); ``` For a full worked example (velocity smoothing over the tail of the drag, scoring, reset), the same idea scales up - measure the release velocity, apply it as an impulse, and let physics carry the object. # User Interface Build 2D panels - labels, sliders, buttons, stacks - from a script, place them in the scene or pin them to the screen, and drive them from your logic. For text that tracks a variable live, see [Live labels](#live-labels) below. Panels built in the editor's [UI editor](/editor/user-interface/) are the same kind of object: a script can find their views by name and change them exactly as described here. For the layout model, the panel settings and how panels render on each device, see the editor's [User Interface](/editor/user-interface/) section. ## Build and place a panel Compose a view tree with the `UI.*` builders, wrap it with `createPanel(...)`, and instantiate it with `scene.createEntity`: ```javascript var panel = createPanel( UI.vStack({ spacing: 12, children: [ UI.label({ text: 'Volume' }), UI.slider({ name: 'vol', value: 0.5, range: [0, 1], sizing: { width: 'fill' } }) ] }), { panelSize: [320, 160], material: 'system' } ).name('controls'); var entity = await scene.createEntity( panel.anchor(Anchor.screenSpace({ alignment: 'bottom', insets: 24 })) ); ``` `Anchor.screenSpace(...)` pins the panel to a screen edge or corner; anchor it in the world instead (e.g. `Anchor.position(...)`) for a panel that lives in the scene. ### Panel options `createPanel(content, options)` takes: | Option | Values | Default | |---|---|---| | `panelSize` | `'auto'` (hug the content), `'fill'` (whole screen, screen-space only), or a size in points: `[width, height]` or `{ width, height }` | `'auto'` | | `material` | `'system'`, `'transparent'`, a hex colour string or `{ r, g, b }` for a solid colour, or `{ prominence: 'standard' \| 'expressive' }` for the system material with a prominence | `'system'` | | `cornerRadius` | points | `8` | | `isScrollable` | `true` to scroll content taller than the panel; needs a fixed `panelSize` | `false` | In the world, about 1360 points make one metre, so `[400, 240]` is roughly 29 × 18 cm. For Liquid Glass, put the panel in screen space and pass `material: { prominence: 'expressive' }`. It shows on iOS, iPadOS and macOS 26 and later. Where it doesn't show, the panel gets an ultra-thin blur instead: - on an earlier version, - with `panelSize: 'fill'`, - on a panel placed in the world. On Apple Vision Pro, panels use the system's window glass. A button gets Liquid Glass with `style: { prominence: 'expressive' }`. The glass takes the button's `backgroundColor` as its tint, or blue for `appearance: 'primary'` and red for `'destructive'`; `'secondary'` and `'custom'` without a colour stay clear. It shows in panels on the screen on iOS, iPadOS and macOS 26 and later. Elsewhere the button keeps its fill: ```js UI.button({ title: 'Walk', style: { appearance: 'custom', foregroundColor: '#FFFFFF', shape: 'capsule', prominence: 'expressive' } }) UI.button({ title: 'Play', style: { appearance: 'primary', shape: 'capsule', prominence: 'expressive' } }) ``` ### Builders | Builder | Options (besides the common ones below) | |---|---| | `UI.label` | `text` (or pass the text as a string), `lineLimit` (default `1`; `null` wraps freely), `textTransform` (`'uppercase'`, `'lowercase'`, `'capitalize'`) | | `UI.button` | `title`, `icon`, `iconPointSize`, `iconOffset` (`[x, y]`, moves the icon without resizing the button) | | `UI.slider` | `value` (default `0.5`), `range: [min, max]` or `min` / `max` (default `0`-`1`), `numberType` (`'float'` or `'integer'`), `step` (`0` = continuous) | | `UI.stepper` | `value` (default `0`), `range` or `min` / `max` (default `0`-`100`), `step` (default `1`), `label` | | `UI.textField` | `text`, `placeholder` | | `UI.segmentedControl` | `segments` (array of titles), `selectedIndex` (default `0`) | | `UI.progressView` | `progress` from `0` to `1`; omit it for a spinner | | `UI.divider` | `thickness` (default `0.5`) | | `UI.shape` | `shape` (default a rounded rectangle with radius 8) | | `UI.spacer` | `minLength` | | `UI.vStack`, `UI.hStack` | `children`, `alignment` (`'leading'`, `'center'`, `'trailing'`, `'top'`, `'bottom'`, `'fill'`; default `'center'`), `distribution` (`'fill'` or `'fillEqually'`), `spacing` (default `8`) | | `UI.carousel` | `children`, `axis` (`'horizontal'` or `'vertical'`), `spacing` (default `8`), `itemSize` (`'fitContent'`, the default, or `'matchLargest'`, which gives every child the length of the longest), `selectedIndex` (default `0`), `snapsToItems` (default `true`), `isScrollLocked`, `showsPageDots`, `neighborScale` and `neighborOpacity` (what a child one step from the middle gets; default `1`), `playsSelectionHaptics` (default `true`) | | `UI.zStack` | `children`, `alignment` (`'center'`, `'top'`, `'bottom'`, `'leading'`, `'trailing'`, `'topLeading'`, `'topTrailing'`, `'bottomLeading'`, `'bottomTrailing'`) | | `UI.annotation` | A marker that opens a card when tapped. `card` (the one view the card shows), `isExpanded` (default `false`), `direction` (`'up'`, `'down'`, `'leading'`, `'trailing'`), `animation` (`'drawStem'`, `'spring'`, `'fade'`), `title` or `image` (an SF Symbol name) inside the marker, `marker`, `stem`, `leader`, `cardStyle`, `shadow` | Every builder also takes: - `name` - for lookup with `findView` - `sizing` - `'auto'`, `'fill'`, a number in points, `[width, height]`, or `{ width, height, maxWidth, maxHeight }` to set each axis - `padding` - a number, `{ horizontal, vertical }`, or `{ top, leading, bottom, trailing }`. Sliders, progress views, dividers and spacers can't apply padding; wrap them in a stack - `safeAreaPadding` - edges whose padding grows by the safe area, such as `['leading', 'bottom', 'trailing']`. It adds nothing while the panel respects the safe area, so pair it with `Anchor.screenSpace({ respectsSafeArea: false })` when a background or photo should reach the screen edge - `background`, `overlay` - views drawn behind or in front of this one. They never change its size or move its neighbours, and they may reach outside it, within the panel - `placement` - where a view in a background or overlay sits: `{ alignment, anchor }`. Each is one of the nine points named as for `UI.zStack`, `[x, y]` from `[0, 0]` top leading to `[1, 1]` bottom trailing, or a `Vector2`. `alignment` is the point on the view it belongs to, `anchor` the point on itself placed there, and both default to the centre. `{ alignment: 'topTrailing' }` centres a badge on the corner; adding `anchor: 'topTrailing'` keeps it inside - `offset`, `style`, `accessibility`, `isHidden`, `isEnabled` In `style`, `font` takes a number for the size, or `{ size, weight, family }`. `foregroundColor` and `backgroundColor` take `'#RRGGBB'`, `'#RRGGBBAA'`, `{ r, g, b, a }` or `{ light, dark }`, and `shape` takes `'rectangle'`, `'capsule'`, `'circle'` or a corner radius in points. Border and shadow are passed through in the format the scene stores them in. For styled panels, design the panel in the editor and change it from a script with `findView`. Labels built in a script default to a single line (`lineLimit: 1`), while labels added in the editor wrap. Pass `lineLimit: null` for wrapping text. **UI.toggle**: Before Scenery 1.3.1, a panel that contains `UI.toggle` fails to load. ## Find and update views Name a view, then reach it later through the object's representation to read or change it: ```javascript var view = entity.representation.findView({ name: 'vol' }); view.setProperty('value', 0.8); // or, with the accessor shorthand: view.value = 0.8; ``` `findView` also accepts a view ID as a string or `{ id }`. The editor copies a view's ID with **Copy Development ID**. These keys can be read and written: | View | Keys | |---|---| | any view | `isHidden`, `isEnabled`, `opacity` | | label | `text` | | button | `title` | | toggle (Switch style) | `isOn` | | annotation | `isExpanded` | | slider | `value`, `minimumValue`, `maximumValue` | | text field | `text`, `placeholder` | | segmented control | `selectedIndex` | | progress view | `progress` | Stepper, image, shape, divider, spacer, web view and the stacks have only the keys every view has. Setting a key a view doesn't have does nothing and logs a warning to the script console. A few details: - `isEnabled = false` stops a view taking touches but doesn't dim it. Set `opacity` as well if it should look disabled. - Setting a label's `text` shows the text as given, without markdown. If the label's authored text contains a `${variable}`, the next change to that variable draws the authored text again. To update a label continuously, give it a `${variable}` and change the variable. ## Add and remove views Add a view made with the `UI.*` builders to a panel that is showing, and take views away again. The other views keep their state, values and animations. ```javascript var cart = entity.representation.findView({ name: 'Cart' }); var badge = cart.add(UI.label({ text: '1', placement: { alignment: 'topTrailing' } }), { to: 'overlay' }); // later badge.remove(); ``` - `view.add(newView, { to, at })` - `to` is `'children'` (the default), `'background'` or `'overlay'`, and `at` the position in that list, last when left out. Returns the added view, or `null` with a console warning when it can't go there. - `view.remove()` - takes the view and everything inside it out of the panel and stops their animations. - `view.background` and `view.overlay` - the views in each list. Setting a list keeps the views it names that are already there, removes the others and adds the new ones. Changes last until the experience ends; the experience as saved stays the same. To build a list from data, author one sample row in the editor, add a copy per item, then hide the sample: ```javascript var list = panel.findView({ name: 'Rooms' }); var sample = list.findView({ name: 'Row' }); ['Kitchen', 'Studio', 'Garden'].forEach(function(room) { var row = list.add(sample.copy()); row.findView({ name: 'Row Name' }).text = room; }); sample.isHidden = true; ``` - `view.copy()` - the view and every view inside it, ready for `add`. Each copy gets new ids and keeps the names. - `view.findView({ name })` - a view inside this one, this view included. Copies share names, so search inside the copy rather than the whole panel. Children can be added to a `vStack`, `hStack`, `zStack` or carousel, but not an annotation's card or a spacer. A carousel keeps its selected child selected when children are added before it. Every view takes a background and an overlay, except a view inside a carousel, an annotation or another background or overlay that has none yet: give it its first one in the editor. ## Animate changes Changes inside `UI.animate` happen animated instead of at once. Write them the same way as without it. ```js const menu = scene.findEntity({ name: 'Menu' }).representation; const rows = menu.findView({ name: 'Office Rows' }); menu.findView({ name: 'Offices' }).on('tap', () => { const opening = rows.isHidden; // Start a group that opens from transparent, so it fades in while the stack opens. if (opening) { rows.opacity = 0; } UI.animate(() => { rows.isHidden = !opening; rows.opacity = opening ? 1 : 0; }, { spring: { duration: 0.35 } }); }); ``` The views around a shown or hidden view move along, and the panel grows or shrinks with them. Views a script adds inside the block fade in. Leave the options out for the system's default spring. ## React to input Subscribe to a view's events: ```javascript entity.representation.findView({ name: 'vol' }).on('valueChanged', function(e) { console.log('slider is now', e.uiValue); }); entity.representation.findView({ name: 'save' }).on('tap', function() { scene.setVariable('saved', true); }); ``` | Event | Views | `e.uiValue` | |---|---|---| | `tap` | button | - | | `valueChanged` | slider, segmented control, carousel | the number, or the selected index | | `scroll` | carousel | the position in the middle as a child index, fractional between two children | | `toggled` | toggle (Switch style), annotation | `true` or `false`; for an annotation, `true` when its card opens | | `textChanged` | text field | the text | Every listener receives `{ uiNodeId, uiInteractionKind, uiValue }`. Taps on labels, images and shapes, and stepper changes, reach a script through an editor event instead: add a **UI Interaction** event on the object with a **Run Script** action, and read `scriptContext.sourceEvent.uiValue`. See [Interaction](/editor/user-interface/interaction). ## Bind a control to a variable `bind` connects a view's value to a variable: ```javascript entity.representation.findView({ name: 'vol' }).bind('value', 'volume'); ``` For **input controls** the binding works both ways: the control writes the variable as the user changes it, and the view updates if the variable changes elsewhere. That covers a slider's `value`, a toggle's `isOn`, a text field's `text`, and a segmented control's or carousel's `selectedIndex`. For **display views** it works one way, from the variable to the view: a label's `text`, a button's `title` and a progress view's `progress`. A label or button binding needs a text variable. Bindings last as long as the panel. Call `unbind(property)` to remove one sooner. Pass `{ scope: 'experience' }` as the third argument to bind to an experience variable instead of a scene variable. Pair a bound control with a live label (below) to show its value. ## Live labels Label text supports inline variable references that resolve **live** - the label re-renders automatically whenever the referenced variable changes. No `scene.on('variableChange', ...)` wiring needed. ```javascript UI.label({ text: 'vol = ${vol}' }) ``` `${vol}` is read from the current scene's variables. If `vol` is unset, the label renders `vol = UNDEFINED`. ### Scopes | Form | Reads from | |------|-----------| | `${name}` | Scene variable (default) - set with `scene.setVariable(name, value)` | | `${g:name}` | Experience variable, kept across scenes - set with `experience.setVariable(name, value)` | ### Filters Pipe the value through a formatter with `|filter` or `|filter(arg)`: | Filter | Use | Example output (input `0.6789`) | |--------|-----|--------------------------------| | `\|fixed(N)` | Trim a float to N decimals (default 2) | `0.68` | | `\|percent(N)` | Multiply ×100, append `%` (default 0 decimals) | `68%` | | `\|time` | Seconds → `m:ss` (or `h:mm:ss` ≥ 1h) | (for `185`) `3:05` | | `\|int` | Truncate toward zero | `0` | | `\|signed(N)` | Always-signed, N decimals (default 0) | `+1` | Filters are numeric - applied to a non-numeric variable, they pass the raw value through unchanged. An unknown filter name does the same. In an experience with translations, the filters write numbers the way the viewer's language does: a German viewer reads `0,68` and `68 %`. ### Markdown Label text also supports inline markdown: `**bold**`, `*italic*` and `` `code` ``. It is applied after variables are filled in, so `**${score}**` shows the score in bold. Headings, lists, links and strikethrough are not drawn. See [Text & Variables](/editor/user-interface/text). ### Example: bound slider with live readout The slider drives the variable; the label reads from it - no subscription code, the label re-renders on every change automatically: ```javascript // Attach to: On Experience Start scene.setVariable('vol', 0.5); var panel = createPanel( UI.vStack({ spacing: 12, padding: 16, children: [ UI.label({ text: 'Volume: ${vol|fixed(2)}' }), UI.slider({ name: 'volume', value: 0.5 }) ] }), { panelSize: [400, 160] } ); var entity = await scene.createEntity(panel); entity.representation.findView({ name: 'volume' }).bind('value', 'vol'); ``` A single label can mix any number of references and plain text; each reference subscribes independently, so any one variable changing re-renders with the current values of all of them: ```javascript UI.label({ text: 'Score: ${g:score|int} , Timer: ${countdown|time}' }) ``` ### Sizing panels with dynamic labels An auto-sized panel re-measures itself when its content changes, so a label that starts empty and later fills in with a wider value makes the panel grow to fit. You can seed a readout with a placeholder and replace it once real data arrives without the text being cut off. A **fixed size** is still worth choosing when you want the panel to stay put: ```javascript createPanel(content, { panelSize: [340, 200] }); ``` A live readout whose value changes width - a counter gaining digits, a place name, a temperature - will otherwise resize its panel each time, which can read as restless if the panel sits in a fixed spot next to other content. Fixed sizing also gives labels room to grow within a stable outline, and is required if you want the panel to be scrollable (`isScrollable: true`). ## Related - [UI](/scripting/api/ui) - the API reference for every view builder - [UIView](/scripting/api/uiview) - the API reference for the views a panel holds # Mesh Instancing Instancing renders many copies of one object in a single draw - thousands of them stay cheap, because the GPU draws the shared mesh once and stamps it at each transform. Use it for fields, crowds, particles, and any procedural scatter. ## Scatter copies Give one object the set of transforms to render it at with `setInstances(Instances.transforms([...]))`. Each transform is a `Vector3` position (or a full transform): ```javascript var base = await scene.createEntity( createBox(0.03, 0.03, 0.03).anchor(Anchor.position(0, 0, -1.5)) ); var spots = []; var count = 1000; var goldenAngle = Math.PI * (3 - Math.sqrt(5)); for (var i = 0; i < count; i++) { var r = 0.4 * Math.sqrt(i / count); var a = i * goldenAngle; spots.push(new Vector3(r * Math.cos(a), 0, r * Math.sin(a))); } base.setInstances(Instances.transforms(spots)); ``` Call `setInstances` again with a new set to re-scatter - for example, from an `On Render` handler or a slider's `valueChanged`. ## Moving instances from a kernel Rebuilding the transform list in JavaScript every frame gets expensive once there are thousands of copies. `entity.instances` hands the transform buffer to a [compute kernel](/scripting/guide/compute) instead, so the work happens on the GPU. It is `null` until `setInstances(...)` has run. ```javascript // Attach to: On Experience Start var instances = base.instances; var threads = 64; var groups = Math.ceil(instances.count / threads); // A `.write` buffer arrives uninitialised, so keep the authored placement to compute from. var authored = Buffer.float32(instances.count * 16, 0); var snapshot = await Kernel.fromSource({ source: ` #include using namespace metal; struct Uniforms { float count; }; kernel void instanceSnapshot(constant Uniforms& U [[buffer(0)]], device const float4x4* src [[buffer(1)]], device float4x4* dst [[buffer(2)]], uint i [[thread_position_in_grid]]) { if (i >= (uint)U.count) { return; } dst[i] = src[i]; } `, functionName: 'instanceSnapshot' }); snapshot.run({ uniforms: new Float32Array([instances.count]), inputBuffers: { src: instances.read }, outputBuffers: { dst: authored }, threadGroups: [groups, 1, 1], threadsPerThreadgroup: [threads, 1, 1] }); ``` A wave kernel then reads that snapshot and writes the live buffer each frame. Each entry is one `float4x4`, column-major, so column 3 holds the translation: ``` // Inside the wave kernel float4x4 m = orig[i]; m[3].y = m[3].y + sin(U.time * 2.0 + length(m[3].xz) * U.spatialFreq) * U.amplitude; out[i] = m; ``` **The buffer is not in metres**: It holds the instanced mesh's own units. On a primitive those are metres, but a model scaled to a fitting box can be hundreds to one - one real model measured 407 buffer units to the metre, so an 8 cm wave written as `0.08` moved each copy by 0.2 mm and looked frozen. `instances.localToMesh` is the conversion. Its scale, element 0, is the factor: ```javascript var perMetre = instances.localToMesh[0]; var uniforms = new Float32Array([ 0, // time 0.08 * perMetre, // an 8 cm wave (Math.PI * 2 / 0.63) / perMetre, // a 63 cm wavelength instances.count ]); ``` `instances.meshToLocal` goes the other way, for reading a distance back out. Both are identity on a primitive, so converting costs nothing and keeps the same script correct on a model. **Models need Flatten switched on**: Instancing works on one mesh, the same way it does everywhere else: three.js instances one geometry, Godot's `MultiMesh` takes one mesh, and Apple's own example collapses a twelve-mesh robot before instancing it. A primitive is always one mesh, so nothing is needed. A model keeps whatever node tree it was exported with, so turn on its **Flatten** adjustment, which loads it as a single mesh. Otherwise nothing is instanced, the console names the meshes it found, and `rep.instances` stays `null`. To instance one node of an unflattened model instead, use `rep.findChild(name).setInstances(...)`. That takes matrices in **that node's own space**, which can be far from metres - a node scaled by its exporter can be thousands of times smaller. The bounds are worked out when `setInstances` runs and do not follow instances a kernel moves, so copies pushed outside the original extent are culled and lose their shadows. ## Instancing vs cloning Instances are **rendering-only**: they share the base object's mesh and material and are not individual entities. You can't tap one, script one, or give one its own physics body. When you need copies that behave independently - each collidable, tappable, or separately animated - use [`entity.clone()`](/scripting/api/objectentity) instead. Rule of thumb: dozens of interactive copies → clone; hundreds or thousands of visual copies → instance. **Shadows on dense fields**: A large instanced field can alias the shared shadow map into streaks. Turn the projected shadow off for the base object so the field stays clean: ```javascript createBox(0.03, 0.03, 0.03).shadow({ directional: false }); ``` Instancing needs iOS 26, iPadOS 26, macOS 26 or visionOS 26. Gate a portable script with `environment.features.has('instancing')` - see [Feature Detection](/scripting/guide/feature-detection). # Gaussian Splats A splat capture is a scanned object or place, stored as hundreds of thousands of tiny coloured blobs rather than as a mesh. Place one in a scene like any other object. From a script you can reach the capture's per-splat data and drive it with a [compute kernel](/scripting/guide/compute), which is how reveals, dissolves and interactive effects are built. ## Reaching a capture `representation.splat` is the handle. It is `null` on any representation that is not a splat, and on a device that cannot render them, so a single check covers both: ```javascript // Attach to: On Experience Start var entity = scene.findEntity({ name: 'Statue' }); await entity.waitUntilReady(); var splat = entity.representation.splat; if (!splat) { console.log('No splat capture here'); return; } console.log(splat.count + ' splats'); ``` While a capture is still loading the handle exists but reports `count === 0`, so wait for the representation before reading anything from it. ## What each splat carries Five attributes, each a buffer you can bind to a kernel: | Attribute | Per splat | Notes | |---|---|---| | `position` | 3 floats | Centre of the blob, in the capture's own space | | `scale` | 3 floats | Size per axis, stored logarithmically | | `rotation` | 4 floats | Orientation, stored `w` first | | `opacity` | 1 float | Stored pre-sigmoid, so `0` is half opaque | | `sphericalHarmonics` | `itemSize` floats | View-dependent colour | Two of those storage formats matter as soon as you write a kernel: - **Scale is a logarithm.** Multiplying a splat's size means *adding* to its scale, so half size is `scale - log(2)`, not `scale * 0.5`. - **Opacity is a logit.** Fade the alpha rather than the stored value, or every splat sits near half opaque for most of the ramp and then pops at the end. `splat.boundingBox` gives the capture's extent, which is what radial and staggered effects key off. Use it rather than the representation's bounding box, which measures an internal proxy. ## Animating a capture Each attribute vends `.read` and `.write` tokens for a kernel's buffer maps, exactly as a [texture](/scripting/api/texturebinding) does. A `.write` buffer arrives uninitialised, so an effect that reads the live buffer and adds to it drifts further from the original every frame and never lands back on the authored look. Copy the pristine attributes into your own buffers once, then compute every frame from that snapshot, and progress 1 writes the originals back exactly. Note the types in the snapshot kernel: a `float3` declaration aligns to 16 bytes and reads garbage against the 12-byte stride, so position and scale are `packed_float3`. The bounds guard matters too, since a thread past the end writes into memory the renderer is using. ```javascript // Attach to: On Experience Start var threads = 64; var groups = Math.ceil(splat.count / threads); var authoredPos = Buffer.float32(splat.count * 3, 0); var authoredScale = Buffer.float32(splat.count * 3, 0); var authoredOpacity = Buffer.float32(splat.count, 0); var snapshot = await Kernel.fromSource({ source: ` #include using namespace metal; struct Uniforms { float count; }; kernel void splatSnapshot(constant Uniforms& U [[buffer(0)]], device const packed_float3* srcPos [[buffer(1)]], device const packed_float3* srcScale [[buffer(2)]], device const float* srcOpacity [[buffer(3)]], device packed_float3* dstPos [[buffer(4)]], device packed_float3* dstScale [[buffer(5)]], device float* dstOpacity [[buffer(6)]], uint i [[thread_position_in_grid]]) { if (i >= (uint)U.count) { return; } dstPos[i] = srcPos[i]; dstScale[i] = srcScale[i]; dstOpacity[i] = srcOpacity[i]; } `, functionName: 'splatSnapshot' }); snapshot.run({ uniforms: new Float32Array([splat.count]), inputBuffers: { srcPos: splat.position.read, srcScale: splat.scale.read, srcOpacity: splat.opacity.read }, outputBuffers: { dstPos: authoredPos, dstScale: authoredScale, dstOpacity: authoredOpacity }, threadGroups: [groups, 1, 1], threadsPerThreadgroup: [threads, 1, 1] }); ``` Your effect kernel then reads those buffers and writes `splat.position.write` and friends each frame. Fading uses the alpha rather than the stored value: ``` // Inside the effect kernel, with `progress` from a uniform float origAlpha = 1.0 / (1.0 + exp(-origOpacity[i])); float alpha = clamp(origAlpha * progress, 1e-6, 1.0 - 1e-6); outOpacity[i] = log(alpha / (1.0 - alpha)); ``` Written values stay put. Once a dispatch lands, the capture keeps those values with no further dispatches, so a one-shot reveal can stop when it finishes. ## Known limitations - **Displacement is clipped.** The volume the renderer culls against is fixed when the capture loads and does not follow splats a kernel moves, so an effect that pushes splats outward meets a hard edge. Gather, swirl and shrink read well; explosions do not. - **A scene holds up to eight captures.** Past that they stop rendering, so budget them like video rather than like props. - **Captures are placed in the editor, not from a script.** There is no script-side factory for one yet, so find a placed capture with `scene.findEntity(...)` and drive it from there. - **Colour is the expensive attribute.** Changing it means rewriting every spherical-harmonic coefficient for every splat, because a `.write` buffer arrives uninitialised. Position, scale and opacity are far cheaper to animate. Splat captures need iOS 27, iPadOS 27, macOS 27 or visionOS 27. Gate a portable script on the handle itself, since `representation.splat` is `null` wherever they are unavailable. # Paths & Splines Build a smooth curve through a set of control points and drive an object along it. Paths are a runtime construct - `scene.createPath(...)` returns a handle you query and hand to `entity.followPath(...)`; they aren't saved in the experience. ## Create a path Pass at least two control points. The curve is a smooth spline through them: ```javascript var path = scene.createPath({ points: [ new Vector3(-0.6, 0, -1.2), new Vector3(-0.2, 0.4, -1.2), new Vector3(0.2, -0.2, -1.4), new Vector3(0.6, 0.3, -1.2) ] }); ``` `createPath` returns `null` if you pass fewer than two valid points. ## Query the curve | Member | Result | | --- | --- | | `path.length` | Total arc length, in metres. | | `path.point(t)` | Position at parameter `t` (0...1 across the whole path). | | `path.pointAtDistance(d)` | Position at arc-length distance `d` (0...`length`) - constant-speed spacing. | | `path.tangent(t)` | Unit direction of travel at parameter `t`. | ```javascript console.log('length', path.length.toFixed(2), 'm'); // Drop a marker every fifth of the way along, evenly spaced by distance. for (var i = 0; i <= 5; i++) { var p = path.pointAtDistance((i / 5) * path.length); await scene.createEntity(createSphere(0.01).anchor(Anchor.position(p.x, p.y, p.z))); } ``` ## Follow a path `entity.followPath(path, options)` animates an object along the curve: ```javascript var box = await scene.createEntity( createBox(0.05, 0.05, 0.05).anchor(Anchor.position(0, 0, 0)) ); box.followPath(path, { duration: 4, constantSpeed: true, // even speed regardless of control-point spacing (default true) alignsToTangent: true, // nose points along the direction of travel (default false) timing: 'easeInOut', // linear | easeIn | easeOut | easeInOut repeat: true // true to loop, or a number of cycles }); ``` **Anchor anywhere**: `followPath` positions the object in world space, so the anchor you give the object only sets its starting reference - the path drives it from there. # Location Read the device's geographic location from a script through `environment.location`. Coarse reads ride the base location grant; precise accuracy is a separate, explicit opt-in. ## Request access and read a fix Ask for access once, then read the current location. Reads never prompt on their own - call `requestAccess()` first. ```javascript await environment.location.requestAccess(); var here = await environment.location.current(); console.log(here.latitude, here.longitude, '±' + here.horizontalAccuracy + 'm'); ``` `current()` resolves a `GeoCoordinate`. On a live fix it also carries `horizontalAccuracy` (metres) and `timestamp`; those are `null` on a coordinate you construct yourself. ## Coordinates: distance and bearing `GeoCoordinate` carries the great-circle helpers, so you can measure against a point of interest without any external maths: ```javascript var target = new GeoCoordinate(48.1372, 11.5756); // latitude, longitude console.log('distance', Math.round(here.distanceTo(target)), 'm'); // metres console.log('bearing', Math.round(here.bearingTo(target)) + '°'); // 0-360 from north ``` ## Watch position Observe location continuously - for example, reveal something when the user gets close: ```javascript var target = new GeoCoordinate(48.1372, 11.5756); var sub = environment.location.watch(function(here) { if (here.distanceTo(target) < 50) { sub.stop(); scene.setVariable('arrived', true); } }); ``` Call `sub.stop()` to end the subscription. ## Precise accuracy The base grant may be coarse. When your experience genuinely needs precise positioning, ask for it explicitly - the user sees a confirmation carrying your `reason`, then the system accuracy prompt: ```javascript var precise = await environment.location.requestPreciseAccess({ reason: 'to guide you to nearby points of interest' }); if (precise) { var fix = await environment.location.current(); } ``` **Ask only when needed**: Request precise accuracy at the moment the feature needs it, not on load - the prompt reads better in context, and coarse location is enough for most distance/region checks. # Tracking `scene.tracking` reads live tracking data from script - articulated hand joints, and face blendshapes when the scene runs in a face context. It is the author-facing entry point for both; you never talk to the underlying provider directly. Two things it is useful for: reading hand or face data **without** planting an anchored object, and controlling when the hand-tracking provider is running. ## Hands Hand tracking is **currently available on Apple Vision Pro only**, and it is opt-in - nothing is tracked until a script asks for it. Gate portable scripts on the feature flag: ```javascript // Attach to: On Experience Start if (environment.features.has("handTracking")) { await scene.tracking.hands.enable(); // resolves when tracking is live } ``` `enable()` rejects if the device cannot track hands or the person declines permission, so handle the rejection rather than assuming it succeeded: ```javascript // Attach to: On Experience Start try { await scene.tracking.hands.enable(); } catch (e) { console.log("Hand tracking unavailable: " + e.message); } ``` Once tracking is live, read the hands each frame: ```javascript // Attach to: On Render var right = scene.tracking.hands.right; // null when that hand isn't tracked if (right) { var tip = right.joints.indexFingerTip.worldTransform.position; console.log("Right index tip: " + tip); } ``` ### Hands reference | Member | Type | Description | |---|---|---| | `enable()` | `Promise` | Opt into hand tracking. Idempotent. Resolves when the provider is running and authorized; rejects if denied or unsupported. | | `disable()` | - | Drop this script's request. Fire-and-forget. | | `isSupported` | `boolean` | Whether this device can track hands at all. | | `active` | `boolean` | Whether the provider is authorized and running. | | `enabled` | `boolean` | Whether this script currently requests hand tracking. | | `left` | [`AnchorData`](/scripting/api/anchordata) \| `null` | Left hand, or `null` when it isn't tracked. | | `right` | [`AnchorData`](/scripting/api/anchordata) \| `null` | Right hand, or `null` when it isn't tracked. | | `anchors` | `Array<`[`AnchorData`](/scripting/api/anchordata)`>` | All currently tracked hands. | **active vs enabled vs a hand being visible**: These are three different questions - `enabled` is what your script asked for, `active` is whether tracking is actually running, and a `left` / `right` of `null` means that particular hand isn't in view right now. Poll `active` to notice permission being revoked or tracking being lost after a successful `enable()`. ## Face Face data needs no opt-in - it is already flowing whenever the scene runs in a face tracking context, so there is nothing to enable. ```javascript // Attach to: On Render var face = scene.tracking.face.current; if (face) { console.log("Face at: " + face.worldTransform.position); } ``` ### Face reference | Member | Type | Description | |---|---|---| | `isSupported` | `boolean` | Whether the scene can deliver face tracking data. | | `active` | `boolean` | Whether a face is currently tracked. | | `current` | [`AnchorData`](/scripting/api/anchordata) \| `null` | The current face anchor - blendshapes and eye transforms - or `null`. | ## Coordinate spaces Joint and face positions are in **world space**. To use them against an object you created, convert into that object's local frame first - see [Coordinate spaces](/scripting/guide/vectors-transforms#coordinate-spaces). ## The lower-level equivalent `scene.tracking` is a convenience layer over `scene.getAnchors(...)`, which stays available if you would rather filter the anchor list yourself: ```javascript // Attach to: On Render var anchors = scene.getAnchors("hand"); for (var i = 0; i < anchors.length; i++) { if (anchors[i].chirality === "right") { console.log("Right hand at: " + anchors[i].worldTransform.position); } } ``` The difference is lifecycle: only `scene.tracking.hands` can turn the hand-tracking provider on and off. `getAnchors("hand")` returns an empty list until something has enabled it. ## Related - [scene.tracking](/scripting/api/scene-tracking) - the API reference for hands and face - [Anchors](/editor/anchors) - anchoring an object to a hand joint instead of reading joints yourself - [Feature Detection](/scripting/guide/feature-detection) - the full capability matrix - [Examples](/scripting/guide/examples) - worked hand-tracking snippets # Game Controllers `scene.gameController` gives a script the game controllers connected to the device: two-hand gamepads such as PlayStation and Xbox controllers on every platform, and, on Apple Vision Pro, tracked spatial controllers such as PlayStation VR2 Sense controllers and styluses such as Logitech Muse. Read the sticks and buttons every frame, react to presses as events, play haptic pulses, and follow where a tracked controller is. Gate a portable script on the feature flag. Every Apple device has controller input; other players may not: ```javascript // Attach to: On Experience Start if (!environment.features.has('gameController')) { console.log('No controller input here, showing touch controls instead'); } ``` Controller input reaches the experience only while its app is in front. ## Connect and disconnect `on('connect')` hands you each controller as it connects. Controllers that were already connected before your script subscribed fire `connect` too, on the next frame, so one handler covers both cases: ```javascript // Attach to: On Experience Start scene.gameController.on('connect', function (controller) { console.log(controller.name + ' connected (' + controller.kind + ')'); }); scene.gameController.on('disconnect', function (controller) { console.log(controller.name + ' disconnected'); }); ``` `scene.gameController.controllers` lists the connected controllers, in the order they connected. A controller that disconnects and reconnects is a new controller with a new `id`. Use `id` to tell two controllers apart, never to recognise a device. Subscriptions end when the scene changes, as `scene.on` subscriptions do. The controllers and their state carry over, and the next scene's script gets `connect` again for every controller already present. ## Read sticks and buttons Each controller keeps its current state in `sticks` and `buttons`, updated in place every frame before `render`. Read them in a render handler: ```javascript // Attach to: On Experience Start var SPEED = 0.5; // metres per second at full deflection var box = scene.findEntity({ name: 'Box' }); scene.on('render', function (e) { var pad = scene.gameController.controllers[0]; var stick = pad && pad.sticks.leftThumbstick; if (!stick || !box) { return; } var p = box.position; box.position = Vector3(p.x + stick.x * SPEED * e.deltaTime, p.y, p.z - stick.y * SPEED * e.deltaTime); }); ``` A stick reads `{ x, y }`, each from -1 to 1, with up as positive `y`. A stick inside its dead zone reads exactly 0. The direction pad reads as a stick too. A button reads `{ pressed, value, touched }`. `value` runs from 0 to 1, so the triggers are analog: ```javascript // Attach to: On Render var pad = scene.gameController.controllers[0]; var trigger = pad && pad.buttons.rightTrigger; if (trigger) { var throttle = trigger.value; // 0 released, 1 fully pulled } ``` A button or stick the controller lacks is `undefined`, so check before you read it. A handler throttled with `scene.on('render', { throttle })` reads the newest state, which can be several frames ahead of its last run. ### Names | Kind | Buttons | Sticks | | --- | --- | --- | | `'gamepad'` | `buttonA`, `buttonB`, `buttonX`, `buttonY`, `leftShoulder`, `rightShoulder`, `leftTrigger`, `rightTrigger`, `leftThumbstickButton`, `rightThumbstickButton`, `buttonMenu`, `buttonOptions` | `leftThumbstick`, `rightThumbstick`, `directionPad` | | `'spatialController'` | `trigger`, `gripButton`, `thumbstickButton`, `buttonA`, `buttonB`, `buttonMenu` | `thumbstick` | | `'stylus'` | `tip`, `primaryButton`, `secondaryButton` | | On a gamepad the face buttons go by position: `buttonA` is the bottom one (Cross on PlayStation, A on Xbox), `buttonB` the right one (Circle, B), `buttonX` the left one (Square, X) and `buttonY` the top one (Triangle, Y). On a spatial controller `buttonA` is the lower face button of that hand and `buttonB` the upper one. On a stylus `tip` is pressed against a surface and its `value` is the pressure, `primaryButton` is the barrel button nearest the tip, and `secondaryButton` the one above it, whose `value` says how hard it is pressed. Read `controller.kind` to pick the names. `controller.hand` is `'left'` or `'right'`: the side a spatial controller is built for, or the hand holding a stylus right now. A spatial controller is announced only once its side is known, so `hand` is set from `connect` on. It is `null` on a gamepad, for a stylus nobody holds, and where accessory tracking isn't allowed; treat `null` as unknown. `controller.name` is for display and logging, so don't branch on it. ## Button events `controller.on('button', ...)` fires when a button changes. Filter by `name` and `phase` to react to one press: ```javascript // Attach to: On Experience Start scene.gameController.on('connect', function (controller) { controller.on('button', { name: 'buttonA', phase: 'began' }, function () { console.log('Jump'); }); }); ``` | `phase` | When | | --- | --- | | `'began'` | The button was pressed. | | `'ended'` | The button was released. | | `'changed'` | Its `value` or `touched` changed while it stayed pressed or released, such as a trigger pulled further. | The event carries `{ controller, name, phase, pressed, value, touched, aim, grip }`, where `aim` and `grip` are the controller's poses in the frame of the change (see below). A trigger is a button, so the same subscription can follow how far it is pulled: ```javascript controller.on('button', { name: 'rightTrigger' }, function (e) { console.log('Throttle ' + Math.round(e.value * 100) + '%'); }); ``` `controller.on('stick', ...)` works the same way and carries `{ controller, name, x, y }`. Every event reports the latest state, at most once per button or stick per frame. Two consequences: - A press and release within one frame is not seen. - A button already held when the controller connected sends no `'began'`; it reports `'ended'` when released. Both `on` methods return an id for `off(id)`. ## Haptics `controller.pulse(intensity, seconds)` plays a haptic pulse. `intensity` runs from 0 to 1: ```javascript controller.on('button', { name: 'buttonA', phase: 'began' }, async function (e) { var started = await e.controller.pulse(0.6, 0.15); if (!started) { console.log('No haptics on this controller'); } }); ``` The promise resolves once the pulse has started, not when it ends. It resolves `false`, with a console warning, where the controller or platform has no haptics or the controller has disconnected. Whether a new pulse cuts a running one short depends on the platform. ## Tracked controllers and styluses On Apple Vision Pro, spatial controllers and styluses are tracked in space. `controller.aim` is the pointing pose: a stylus tip, or where a spatial controller points. `controller.grip` is where the hand holds a spatial controller; a stylus has none. Each is a pose, `null` while the position isn't tracked: | Pose member | Type | Description | | --- | --- | --- | | `position` | `Vector3` | In the space of `entity.worldPosition`. | | `rotation` | `Rotation` | As `entity.worldRotation`; the pose points along its -z. | | `velocity` | `Vector3` | Metres per second. | | `angularVelocity` | `Vector3` | Radians per second around the vector's axis. | A new pose arrives every frame; one you keep doesn't change. Follow a controller in a render handler: ```javascript // Attach to: On Experience Start var sword = scene.findEntity({ name: 'Sword' }); scene.on('render', function () { var right = scene.gameController.controllers.find(function (c) { return c.kind === 'spatialController' && c.hand === 'right'; }); var grip = right && right.grip; if (grip && sword) { sword.worldPosition = grip.position; sword.worldRotation = grip.rotation; } }); ``` To attach an object without a script, anchor it to the accessory instead: `Anchor.accessory({ kind, hand, location })` in a script, or the Spatial Accessory anchor in the editor. An anchored object hides while the accessory isn't tracked. Gate pose reads on `environment.features.has('accessoryTracking')`; where it is false, poses read `null`. Tracking asks the person for permission the first time a script reads a pose or a hand, or lists or subscribes to controllers while a spatial controller is connected. If they decline, poses read `null` and the console says so once. ## Controllers and the camera Outside AR, such as on the Mac and in the preview, a game controller also drives the camera: the left stick and the triggers move it, and the right stick orbits. To use those inputs yourself, take them over with `scene.camera.gamepad`: ```javascript // Attach to: On Experience Start scene.camera.gamepad.move = false; // the left stick and triggers are now yours; the right stick still orbits ``` See [Camera](/scripting/guide/camera) for following an object with the camera. ## Reference | Member | Type | Description | | --- | --- | --- | | `scene.gameController.controllers` | `Array` | Connected controllers, in connection order. | | `scene.gameController.on(type, fn)` | `string` | `'connect'` or `'disconnect'`; `fn` receives the controller. Returns an id. | | `scene.gameController.off(id)` | | Removes a subscription. | | `controller.id` | `string` | Unique for this connection. | | `controller.kind` | `string` | `'gamepad'`, `'spatialController'` or `'stylus'`. | | `controller.hand` | `string \| null` | `'left'`, `'right'` or `null` (unknown). | | `controller.aim` | `Pose \| null` | The pointing pose of a spatial controller or stylus, `null` while untracked. | | `controller.grip` | `Pose \| null` | Where the hand holds a spatial controller, `null` on a stylus and while untracked. | | `controller.name` | `string` | For display and logging. | | `controller.isConnected` | `boolean` | `false` once disconnected; its buttons then read released and its sticks centred. | | `controller.buttons[name]` | `{ pressed, value, touched }` | Current state, or `undefined` when the controller lacks the button. | | `controller.sticks[name]` | `{ x, y }` | Current state, or `undefined` when the controller lacks the stick. | | `controller.on(type, [options], fn)` | `string` | `'button'` or `'stick'`, with an optional `{ name, phase }` filter. Returns an id. | | `controller.off(id)` | | Removes a subscription. | | `controller.pulse(intensity, seconds)` | `Promise` | Plays a haptic pulse; resolves once it has started. | ## Related - [scene.gameController](/scripting/api/scene-gamecontroller), [GameController](/scripting/api/gamecontroller) and [Pose](/scripting/api/pose) - the API reference - [Camera](/scripting/guide/camera) - a follow camera for a character - [Feature Detection](/scripting/guide/feature-detection) - the full capability matrix - [Examples](/scripting/guide/examples#roll-a-ball-with-a-game-controller) - a small rolling-ball game # Camera `scene.camera` points the camera at objects in the scene. Follow a character as it moves, turn toward one object after another for a guided tour, then hand the camera back to the viewer. ## Where it applies The camera follows a script only where the experience drives its own camera: on the Mac, and in the preview outside AR on iPhone and iPad. Read `scene.camera.kind` to find out which case you are in: | `kind` | Where | What the calls do | | --- | --- | --- | | `'orbit'` | Mac, and the preview outside AR | Take effect right away. | | `'device'` | AR on iPhone and iPad | The device is the camera. Calls are kept and take effect once the view leaves AR, with one console warning. | | `'device'` | Apple Vision Pro | The wearer's head is the camera. `follow` and `lookAt` return `false` with a warning. | `kind` changes when the preview switches in or out of AR. `environment.features.has('cameraControls')` is `false` on Apple Vision Pro, so gate a portable script on the flag: ```javascript // Attach to: On Experience Start if (environment.features.has('cameraControls')) { scene.camera.follow(scene.findEntity({ name: 'Hero' })); } ``` ## Units Framing angles (`azimuth`, `elevation`, `elevationRange`) are in degrees. Distances and offsets are in metres, damping in seconds. `Rotation` values elsewhere in scripting are radians, so don't pass one here. ## Follow a character `follow` keeps an object in view. The camera's orbit moves along with the object, and the viewer can still drag or use the right stick to swing around it: ```javascript // Attach to: On Experience Start var hero = scene.findEntity({ name: 'Hero' }); scene.camera.follow(hero, { distance: 1.6, // metres from the aim point elevation: 30, // degrees above the horizon offset: Vector3(0, 0.1, 0), // aim 10 cm above the object's origin verticalDamping: 2, // seconds; slower in height, so a jump doesn't bob the view elevationRange: [10, 50], // degrees the viewer can orbit between zoom: { min: 0.8, max: 3 } // metres the viewer can zoom between }); ``` While the camera follows, keys, two-finger pan and the left stick no longer move it. Clicking the right stick returns to the framing the follow started with. | Option | Default | Description | | --- | --- | --- | | `distance` | as now | Metres from the camera to the aim point. | | `azimuth` | as now | Degrees around the object. 0 looks toward -z. | | `elevation` | as now | Degrees above the horizon. | | `offset` | `Vector3(0, 0, 0)` | World-space metres from the object's origin to the point the camera aims at, such as above a character's feet. | | `damping` | about 1.5 | Seconds the camera takes to settle after the object moves. `0` is rigid. | | `verticalDamping` | `damping`, or about 3.8 | The same for height. | | `elevationRange` | `[0, 60]` | `[min, max]` degrees the viewer can orbit between. | | `orbit` | `true` | Whether dragging and the right stick orbit. | | `zoom` | `true` | Whether pinch and scroll change the distance. Pass `{ min, max }` in metres to limit it, or `false` to switch it off. | Leave out `distance`, `azimuth` or `elevation` to keep the current view for that value. ## Look at objects `lookAt` turns the camera toward an object and keeps it turned there while the object moves. The camera stays where it is, or stands at `from`. Dragging, zooming and the right stick's click do nothing until `release()`. It takes `from`, `offset` and `damping`, with the same units and defaults as `follow`. A guided tour, where the viewer drives the camera again at the end: ```javascript // Attach to: On Experience Start var STOP_SECONDS = 4; var VIEWPOINT = Vector3(0, 0.4, 1.2); // metres in front of and above each exhibit if (scene.camera.kind === 'orbit') { for (var i = 1; i <= 3; i++) { var exhibit = scene.findEntity({ name: 'Exhibit ' + i }); scene.camera.lookAt(exhibit, { from: exhibit.worldPosition.add(VIEWPOINT), damping: 0.8 }); await wait(STOP_SECONDS); } scene.camera.release(); } else { console.log('In AR the visitor walks the tour themselves'); } ``` ## Hand the camera back `release()` hands the camera back to the viewer from where it is now. `scene.camera.mode` reports what the last call set up: `'free'`, `'follow'` or `'lookAt'`. A follow or look-at also ends on its own: - when the scene changes - when the object leaves the scene, with a console warning `mode` then reads `'free'` again. ## Game controller sticks Outside AR a game controller drives the camera. `scene.camera.gamepad` decides which of its inputs the camera keeps: | Property | Inputs | Default | | --- | --- | --- | | `move` | The left stick and the triggers move the camera. | `true` | | `orbit` | The right stick orbits; its click resets the view. | `true` | Set one to `false` to read those inputs in your own script: ```javascript // Attach to: On Experience Start // The left stick walks the character; the right stick still orbits the camera. scene.camera.gamepad.move = false; ``` Both return to `true` when the scene changes. While the camera follows or looks at something, `move` has no effect anyway. See [Game Controllers](/scripting/guide/game-controllers) for reading the sticks. ## Reference | Member | Type | Description | | --- | --- | --- | | `scene.camera.kind` | `string` | `'orbit'` where the experience drives its own camera, `'device'` where the device is the camera. | | `scene.camera.mode` | `string` | `'free'`, `'follow'` or `'lookAt'`. | | `scene.camera.gamepad` | `{ move, orbit }` | Which game controller inputs the camera keeps. | | `scene.camera.follow(target, options)` | `boolean` | Keep an object in view. `true` once the camera follows, including in AR. | | `scene.camera.lookAt(target, options)` | `boolean` | Turn toward an object. `true` once the camera looks at it, including in AR. | | `scene.camera.release()` | | Hand the camera back to the viewer. | `target` is an object or representation, such as the result of `scene.findEntity(...)`. ## Related - [scene.camera](/scripting/api/scene-camera) - the API reference - [Game Controllers](/scripting/guide/game-controllers) - sticks, buttons and haptics - [Feature Detection](/scripting/guide/feature-detection) - the full capability matrix - [Examples](/scripting/guide/examples#roll-a-ball-with-a-game-controller) - a follow camera in a small game