Base class for all plugins. Extend this to create your plugin.
export class MyPlugin extends ArrivalScript {
static scriptName = "myPlugin";
}| Property | Type | Description |
|---|---|---|
this.entity |
pc.Entity |
The entity this plugin is attached to |
this.app |
pc.Application |
The PlayCanvas application |
this.position |
pc.Vec3 |
World position (get/set) |
this.localPosition |
pc.Vec3 |
Local position (get/set) |
this.rotation |
pc.Vec3 |
Euler rotation in degrees (get/set) |
Avoid reserved plugin property names such as enabled, app, and entity.
Which receiver?
this.*is your vibe — entity, params, 2D UI, input locks, logging, auto-cleaned listeners. Everything about the world isArrivalSpace.*(see ArrivalSpace below): player, camera, physics, loading, materials, avatars, space, files. SoArrivalSpace.getPlayer(), neverthis.getPlayer().Note
this.on/this.fireare pc.Script's own emitter, not the plugin event bus — that isArrivalSpace.fire/on/off/once.
Find a child entity by name. For the whole scene use ArrivalSpace.findEntity(name)
or ArrivalSpace.findByTag(tag).
Subscribe to changes in the entity the local player is standing on.
Callback: (currentEntity, previousEntity) => {}
Returns: Function unsubscribe function
Subscribe once to the next standing-object change.
Remove a standing-object change listener registered with this script as scope.
Listen for a keyboard key-down event.
key can be a key string such as "e" or a PlayCanvas key code.
With { consume: true } the key is this vibe's: the platform (walking, its shortcuts) and vibes
listening without consume don't see it — unless the callback returns false for that press.
Typing into a text field is never taken. Requires ArrivalSpace.VERSION >= 1.31.0.
// Esc closes this vibe's panel, and only that while it is open
this.onKeyDown('ESCAPE', () => {
if (!this._panelOpen) return false; // not ours this time: let it through
this.closePanel();
}, { consume: true });Returns: Function unsubscribe function
Listen for a keyboard key-up event. options.consume as for onKeyDown.
key can be a key string such as "e" or a PlayCanvas key code.
Returns: Function unsubscribe function
Lock the mouse to this vibe: the cursor hidden, every move handed to move(dx, dy, event), until
the player presses Esc (the browser's own way out) or the vibe lets go. While the vibe holds it,
the platform's camera leaves the mouse alone — no look, and its right click neither toggles nor
steals the lock. Ask from a click or a key (browsers grant a lock only on a user gesture). One lock
at a time page-wide; a new one ends the last. Let go automatically when the vibe is unloaded.
Requires ArrivalSpace.VERSION >= 1.31.0.
| Param | Type | Description |
|---|---|---|
handlers.move |
(dx, dy, event) => void |
Each mouse move while locked (pixels) |
handlers.release |
() => void |
The lock ended without the vibe asking: Esc, another lock, focus lost, or refused |
Returns: () => void — let go of the lock (release is not called for that).
// A control stick taken in hand: the mouse flies it, Esc lets go
ArrivalSpace.onEntityClick(this.stick, () => {
this._letGo = this.requestPointerLock({
move: (dx, dy) => {
this.x = pc.math.clamp(this.x + dx / 600, -1, 1);
this.y = pc.math.clamp(this.y + dy / 600, -1, 1);
},
release: () => { this.x = this.y = 0; },
});
});The mouse cursor over the 3D view while this vibe wants one — 'pointer', 'grab', 'grabbing',
'crosshair', any CSS cursor; '' or null gives it back. Shows over the platform's own hover
cursor; among vibes the last one set shows. Given back automatically when the vibe is unloaded.
Requires ArrivalSpace.VERSION >= 1.31.0.
ArrivalSpace.onEntityHover(this.knob, { enter: () => this.setCursor('grab'), leave: () => this.setCursor(null) });Call fn(camera) every frame once the camera is where it will be drawn from: after every
script's update and postUpdate (the platform's camera included), right before the frame is
drawn. Place your own camera there (it then wins over the platform's), or read the final pose for
anything that has to match the picture — labels over objects, screen-space effects, picking by
projection. Removed automatically when the vibe is unloaded. Requires ArrivalSpace.VERSION >= 1.31.0.
Returns: () => void — unsubscribe.
this.onCameraPlaced((cam) => {
cam.setPosition(this._eye.getPosition());
cam.setRotation(this._eye.getRotation());
});Debug drawing that shows only with ?debug on the address (?debug=myVibe,other: only those
script names); otherwise every call does nothing and costs nothing. Draw each frame what should
show that frame (from update) — nothing has to be cleared. Requires ArrivalSpace.VERSION >= 1.31.0.
| Call | Draws |
|---|---|
this.debug.line(from, to, color?) |
A line between two world points (pc.Vec3), over everything |
this.debug.cross(at, size = 0.1, color?) |
Three axis lines size metres long through a world point |
this.debug.text(at, text, color?) |
A label at a world point (pc.Vec3) or a screen point ({x, y}, CSS px) |
this.debug.enabled |
Whether it draws (skip building debug data when false) |
Colours are CSS colour strings ('#f0f', 'lime') or a pc.Color; the default is magenta.
update() {
this.debug.cross(this._target.getPosition(), 0.2, 'lime');
this.debug.text(this._target.getPosition(), `hp ${this._hp}`);
}Get (or create) this script's 2D UI container.
Create a 2D HTML element in your script UI container.
Create a styled fixed-position 2D panel (top-left, top-right, bottom-left, bottom-right, center).
Remove all 2D UI created by this script.
Show/hide this script's 2D UI container.
Temporarily lock/unlock game pointer input while interacting with UI. Interactive createUI elements lock input on their own while hovered; that lock is tracked separately, so leaving UI never releases a lockInput() lock. A createUI element whose CSS sets pointer-events: none is click-through and doesn't lock.
Both halves by default; ask for one alone (ArrivalSpace.VERSION >= 1.31.0):
| Option | Default | Locks |
|---|---|---|
pointerLock |
true |
The platform's camera doesn't look or orbit with the mouse, and its right click doesn't lock the mouse — for a view the vibe drives itself (a cockpit, a puzzle) |
sceneTouch |
true |
Clicks and hovers don't reach the scene (NPCs, click-to-walk, onEntityClick) |
// Seated in a cockpit: the camera is ours, the cockpit's switches still clickable
this.lockInput({ pointerLock: true, sceneTouch: false });Temporarily lock/unlock movement keys while typing in UI fields. When locking, any in-progress avatar movement is zeroed out. On mobile, the virtual joystick values remain readable via getLeftStick() / getRightStick() but avatar movement events are suppressed.
boolean — true if running on a touch/mobile device.
Get the current left virtual joystick input (movement stick on mobile).
Returns: { x: number, y: number } — values from -1 to 1. x = left/right (strafe), y = forward/back. Returns {x: 0, y: 0} on desktop or when no touch is active.
Get the current right virtual joystick input (camera stick on mobile).
Returns: { x: number, y: number } — raw stick position. Returns {x: 0, y: 0} on desktop or when no touch is active.
Load a GLB/GLTF into the scene as this vibe's own model. Returns Promise<{ entity, asset }>.
It's an instance-method wrapper around ArrivalSpace.loadGLB(url, options) that wires the model to this vibe in two ways:
- It parents the model to this plugin's entity, so the editor gizmo moves, rotates and scales it, and it unloads with the vibe.
- Clicking it in edit mode selects this plugin's entity for editing (the vibe's host entity is injected as the internal selection target).
Prefer this.createModel(...) over raw ArrivalSpace.loadGLB(...) whenever a plugin spawns its own model. Raw loadGLB with no parent drops the GLB on the scene root: the gizmo then moves the vibe's entity while the visible mesh stays where it was, which looks like a broken editor.
Accepts the same options as loadGLB (parent, name, scale, position, rotation, castShadows, transparentDepthPrepass, onLoad, …). position and rotation are relative to this vibe's entity and accept [x, y, z], { x, y, z } or a pc.Vec3. Pass parent explicitly to attach the model somewhere else — a bone, a sub-container, or pc.app.root for a world-space object that must not inherit the entity's transform.
async initialize() {
// Parented to this vibe by default — gizmo-movable, clickable-to-edit.
const { entity } = await this.createModel('https://.../thing.glb', {
scale: 2,
position: [0, 1, 0], // 1 m above the vibe's entity
});
this._model = entity;
}Convenience wrapper for ArrivalSpace.createNPC(options?).
Set onClick when you want the NPC to handle clicks with your own callback.
Force the host editor to re-read this plugin's parameter schema.
Replace dropdown options for a parameter at runtime.
Append deduped dropdown options for a parameter at runtime.
Get the current dropdown options array for a parameter.
export class MyPlugin extends ArrivalScript {
static scriptName = "myPlugin";
initialize() {
// Called once when plugin starts
}
update(dt) {
// Called every frame
}
postUpdate(dt) {
// Called after all update() methods
}
onPropertyChanged(name, value, oldValue) {
// Called when an editor property changes
}
onInstall(ctx) {
// Called ONCE, right after a user adds this vibe to the space
// in-app. Run one-time setup here (e.g. open a config panel).
}
onEntityMoved(position, rotation) {
// Called when this vibe's entity is moved/rotated in the editor.
// Re-anchor anything you spawned separately from this.entity.
}
onEditModeChanged(isEditing, context) {
// Called when this vibe's in-app editor opens/closes.
// Toggle editor-only helpers, pause gameplay, etc.
}
destroy() {
// Called when plugin is removed/destroyed
}
}Optional. Fired once — right after a user adds this vibe to the space in-app (library install, drag-drop, or upload), in the browser where they added it. Use it to run a one-time setup flow: e.g. open your own configuration panel and collect settings.
- In-app add only. It's tied to the user actually creating the entity in their browser — not the per-load path. So it never fires on reload, never for other visitors, and never for CLI/MCP deploys (which create the entity through the API and never run the in-app create flow). That makes it safe to show setup UI: the person who just added it is right there.
- No re-fires, no flag. Reloads don't re-create the entity, so there's nothing to dedupe — no persisted marker, no owner-check.
- May be async. Returning a promise is fine; the install flow doesn't block on it. An abandoned or cancelled setup simply does nothing — if you want to re-prompt, track that yourself.
- Pre-set the vibe's parameters. The cleanest way to persist setup is to write the vibe's own editor parameters with
this.setParams({...})— they show in the parameter panel, are applied automatically on every load, and are seen by every visitor. Keep params small (numbers, strings, colors); save documents such as a level layout to a file withArrivalSpace.fs. - Deploying via CLI/MCP? Set the vibe's
paramsdirectly at deploy time instead of relying on this hook — seedocs/00-agent-quickstart.md.
ctx: { isFirstInstall: true, entityId: string, spaceId: string }.
async onInstall(ctx) {
// Owner just installed this vibe — open a one-time setup panel
this._openSetupPanel();
}Requires ArrivalSpace.VERSION ≥ 1.12.0 (feature-detect if you target older clients). See first-install-setup.mjs for a complete example.
Optional. Fired when this vibe's placed entity is moved or rotated in the editor, right after the transform-gizmo gesture finishes.
- On finish, not during the drag. It fires once on mouse-up (gizmo commit), not every frame while dragging — so re-anchoring here won't jitter.
positionis the new world position{x, y, z};rotationis Euler angles in degrees{x, y, z}. Either can benullif that part didn't change — guard before reading, or fall back tothis.entity.getPosition()/getEulerAngles().- You usually only need this for detached content. Anything parented to
this.entitymoves with it automatically. Reach for this hook when you spawned something separately — an NPC (its own scene entity), a rigidbody you drive withteleport(), or sub-entities placed on the scene root — that would otherwise stay at its original spot until a reload.
onEntityMoved(position) {
// NPC is a separate entity — teleport it to the vibe's new anchor.
const pos = position || this.entity.getPosition();
if (this._npc) {
this._npc.stop();
const rb = this._npc.entity.rigidbody;
if (rb && rb.enabled) rb.teleport(new pc.Vec3(pos.x, pos.y, pos.z));
else this._npc.entity.setPosition(pos.x, pos.y, pos.z);
}
}See lamp.mjs (teleports its own rigidbody) and npc-character.mjs (repositions a spawned NPC).
Optional. Fired when this vibe's in-app editor opens or closes for its entity — i.e. when the user selects it (opens the creator/settings panel) or deselects it.
isEditingistruewhile the editor is open for this vibe,falsewhen it closes.contextis the editor context object (creator-badge state), ornull.- Also fires once right after
initialize()if the vibe finished loading while already selected — so a plugin that loads into an open editor still learns it's in edit mode. - Also fires with
falseif the entity is unloaded while being edited. - Use it to show editor-only helpers (gizmos, bounds, guides), pause gameplay or physics while the owner is arranging the scene, or reveal debug UI that shouldn't appear for visitors.
The same transitions are mirrored on the plugin event bus if you prefer events over the hook — subscribe with this.on(...) and unsubscribe in destroy():
plugin:editModeChanged— payload{ isEditing, entityId, context }plugin:editModeEnter/plugin:editModeExit— same payload, split by direction
onEditModeChanged(isEditing) {
// Show a wireframe helper only while the owner is editing this vibe.
if (this._helper) this._helper.enabled = isEditing;
}Persist the vibe's own editor parameters — the canonical params stored on the entity — from plugin code. This is what the editor's parameter panel writes; calling it yourself (e.g. from onInstall) is how you pre-configure a vibe so the value:
- shows up in the parameter panel,
- is applied automatically onto
this[name]on every load (beforeinitialize()), - is seen by every visitor, and
- survives reloads — no side store needed.
Only declared plugin properties are valid names. The live this[name] is updated too, but your own onPropertyChanged() is not called (you're the one setting it, so apply any side effects yourself). Returns a promise that resolves once persisted.
Persists only when the current user can edit the space (ArrivalSpace.canEditSpace()). For everyone else only the live value changes, nothing is sent to the server, the promise resolves false and a console error names the attempted write. The space agent's inspector browser never persists either. Values equal to the stored ones are not re-uploaded (resolves true), unless an earlier { persist: false } change is still unsaved.
Size limit: each save uploads the entity's whole data (all params, JSON-encoded) and is capped at 400 KB; larger saves fail with HTTP 413. A param holding a JSON string counts with its escaping (every " becomes \"), so ~350 KB of JSON text already exceeds it. Space files (ArrivalSpace.fs) take up to 5 MB per file.
// One value:
await this.setParam('greeting', 'Hello!');
// Several at once (single upload):
await this.setParams({ greeting: 'Hello!', accent: '#ff0066' });
// Batch without uploading, then persist once:
await this.setParam('a', 1, { persist: false });
await this.setParam('b', 2, { persist: false });
await this.save();save() persists the current params without changing any values. Requires ArrivalSpace.VERSION ≥ 1.12.0.
Global utilities available anywhere. No import required.
Current plugin API version string.
A dedicated event bus for inter-plugin communication. Use namespaced event names (e.g. "myGame:event") to avoid collisions.
This is separate from ArrivalSpace.net (which is for multiplayer messaging between players). The event bus is local — events are only received by plugins running in the same client.
Fire an event. All plugins listening via on() or once() will be called.
ArrivalSpace.fire("scavenger:item:ready", this);Listen for an event.
ArrivalSpace.on("scavenger:item:ready", (item) => {
console.log("New item:", item.label);
});Remove an event listener. Pass the same function reference used in on().
Listen for an event once. The listener is automatically removed after the first call.
Pattern — Controller + Items:
Use the event bus when multiple plugin instances need to discover each other. A common pattern is a controller plugin that manages game logic and item plugins that register themselves:
// Item plugin (many instances):
initialize() {
ArrivalSpace.fire("myGame:item:ready", this);
}
destroy() {
ArrivalSpace.fire("myGame:item:removed", this);
}
// Controller plugin (one instance):
initialize() {
// Discover items already in the scene
const plugins = ArrivalSpace.getPlugins();
const items = plugins.filter(p => p.name === "My Item");
// Listen for items that load after us
ArrivalSpace.on("myGame:item:ready", (item) => { ... });
}See scavenger-hunt.mjs and scavenger-item.mjs for a complete working example.
Load a GLB/GLTF 3D model.
| Option | Type | Default | Description |
|---|---|---|---|
parent |
pc.Entity |
- | Parent entity. Use this.entity so the model is auto-destroyed on unload |
name |
string |
- | Entity name |
scale |
number |
1 |
Uniform scale |
position |
{x,y,z} |
- | Local position |
rotation |
{x,y,z} |
- | Euler rotation |
transparentDepthPrepass |
boolean |
false |
Texture-transparent parts draw only where they are the model's front-most layer, so a model whose solid parts use a blended material doesn't show its own far side or inside (the model entity's Transparent Depth Prepass setting; Blender's "Transparency Overlap" off). Plain glass with one overall opacity is not affected. 1.38.0 |
Returns: Promise<{ entity: pc.Entity, asset: pc.Asset }>
Load a Gaussian Splat. Supports .ply, .sog, and .spz (decompressed on-the-fly).
| Option | Type | Default | Description |
|---|---|---|---|
parent |
pc.Entity |
- | Parent entity. Use this.entity for auto-cleanup |
name |
string |
'LoadedSplat' |
Entity name |
scale |
number |
1 |
Uniform scale |
position |
{x,y,z} |
- | Local position |
rotation |
{x,y,z} |
- | Euler rotation |
Returns: Promise<{ entity: pc.Entity, asset: pc.Asset }>
const { entity } = await ArrivalSpace.loadSplat('https://example.com/scene.ply', {
parent: this.entity,
scale: 0.5,
position: { x: 0, y: 1, z: 0 },
});Important: Always parent loaded assets to this.entity (not this.app.root). Children of this.entity are automatically destroyed when the plugin is removed. Entities on the scene root will persist as orphans.
Load a texture/image.
Returns: Promise<{ texture: pc.Texture, asset: pc.Asset }>
Play positional or non-positional audio. url is an audio file's URL, or "sfx:<name>" for a
built-in game sound (API 1.37.0): coin, jump, shoot, hit, explosion, click, pop, ding, success, fail, powerup, whoosh -
chiptune-style, synthesised in the browser on first use, each under 1.2 s; pitch varies them.
| Option | Type | Default | Description |
|---|---|---|---|
entity |
pc.Entity |
- | Attach sound to an entity |
position |
{x,y,z} |
- | World position if no entity |
volume |
number |
1 |
Volume (0-1) |
loop |
boolean |
false |
Loop playback |
pitch |
number |
1 |
Playback speed |
refDistance |
number |
1 |
3D falloff start |
maxDistance |
number |
100 |
3D falloff end |
rollOffFactor |
number |
1 |
Falloff intensity |
positional |
boolean |
true |
Enable 3D positional audio |
Returns: Promise<{ entity: pc.Entity, slot: pc.SoundSlot }>
Speak text with an AI voice (OpenAI gpt-4o-mini-tts), streamed: playback starts while the
rest is still being generated - about 0.5-2 s for a new line, about 0.4 s for a line spoken
before (finished lines are cached, also across visitors). Any language the voices speak
(Arabic, Hindi, German, ...); the voices are tuned for English. Requires
ArrivalSpace.VERSION >= 1.23.0.
| Option | Type | Default | Description |
|---|---|---|---|
voice |
string |
'marin' |
alloy, ash, ballad, coral, echo, fable, onyx, nova, sage, shimmer, verse, marin, cedar |
instructions |
string |
- | How to say it: tone, accent, pace, emotion (up to 1000 characters) |
speed |
number |
1 |
0.25 to 4 |
entity |
pc.Entity |
- | Speak from this entity; follows it, stops when it is destroyed. An avatar (an NPC's entity) moves its mouth with the voice |
position |
{x,y,z} |
- | Or from a fixed world position |
volume |
number |
1 |
|
refDistance / maxDistance / rollOffFactor |
number |
1 / 100 / 1 |
3D falloff, as in playSound |
positional |
boolean |
with entity or position |
3D positional audio |
Returns: { done, stop(), playing, level, error }
done:Promise<boolean>-truewhen spoken to the end,falsewhen stopped or failed. Never rejects.stop(): stops at once.playing:trueuntil it ends or is stopped.level: current loudness,0..1- e.g. to open a mouth or pulse a light.error: why it failed (nullotherwise), e.g. an unknown voice or the speaker's monthly allowance being used up.
Limits: each listener's client generates the speech under that listener's own account, up to a monthly allowance of new speech (lines served from the cache don't count). A text over 4096 characters is split into requests after sentence ends. OpenAI's usage policy requires telling listeners that the voice is AI-generated.
// an NPC greets the player once and moves its mouth while talking
const speech = ArrivalSpace.speak("Welcome to the market!", {
entity: this.npc, voice: "cedar", instructions: "Warm, unhurried tour guide.",
});
this._speech = speech; // read speech.level in update()
await speech.done;
// in destroy(): this._speech?.stop();Example: examples/speaking-sign.mjs - a sign that speaks when you come close and glows with its voice.
Create a pc.StandardMaterial.
| Option | Type | Default | Description |
|---|---|---|---|
diffuse |
pc.Color or {r,g,b} |
- | Base color |
emissive |
pc.Color or {r,g,b} |
- | Emissive color |
emissiveIntensity |
number |
1 |
Emissive multiplier |
diffuseMap |
pc.Texture |
- | Base color texture |
normalMap |
pc.Texture |
- | Normal map |
emissiveMap |
pc.Texture |
- | Emissive texture |
opacity |
number |
1 |
Transparency amount |
transparent |
boolean |
false |
Enable transparency |
blendType |
'normal' | 'additive' | 'multiply' |
'normal' |
Blend mode (used when transparent) |
useLighting |
boolean |
true |
Lit vs unlit |
doubleSided |
boolean |
false |
Disable backface culling |
metalness |
number |
0 |
Metalness value |
gloss |
number |
0.5 |
Glossiness value |
Returns: pc.StandardMaterial
- Call
mat.update()after changing any property or map, or nothing changes on screen. - A StandardMaterial's own
transparentis read-only: assigning it throws. SetblendType(pc.BLEND_NORMAL|pc.BLEND_ADDITIVE|pc.BLEND_PREMULTIPLIED, defaultpc.BLEND_NONE) andopacity;createMaterial'stransparentoption does exactly that. Overlapping glass or backdrops also needmat.depthWrite = false. - A StandardMaterial reads vertex normals whenever the space has a skybox,
useLighting: falseincluded. On WebGPU a mesh without normals turns the whole frame black: build them withmesh.setNormals(pc.calculateNormals(positions, indices))(lines: any constant normal). - A custom shader that fails to compile is logged as an error with the GL message (console and
getVibeLogs()); meshes drawn with it are not rendered.
Create a CSS3/iframe-based 3D panel. Best for interactive controls (buttons, forms, input fields).
| Option | Type | Default | Description |
|---|---|---|---|
position |
{x,y,z} |
required | World position |
width |
number |
1 |
Panel width |
height |
number |
0.5 |
Panel height |
html |
string |
- | Custom HTML content |
text |
string |
'' |
Simple text fallback |
rotation |
{x,y,z} |
{0,0,0} |
Euler rotation |
backgroundColor |
string |
#222222 |
Panel background |
textColor |
string |
#ffffff |
Text color |
fontSize |
string |
24px |
Font size for text mode |
pixelsPerUnit |
number |
300 |
UI texture density |
billboard |
boolean |
false |
Face camera every frame |
interactive |
boolean |
false |
Enable pointer events |
disableOnLook |
boolean |
true |
Disable mouse interaction while camera look is active |
Returns: pc.Entity (with helper panel.updateContent(newOptions))
Create a texture-rendered 3D panel with alpha support. Best for transparent overlays and link interaction.
| Option | Type | Default | Description |
|---|---|---|---|
position |
{x,y,z} |
required | World position |
html |
string |
required | HTML content to render |
width |
number |
1 |
Panel width |
height |
number |
0.5 |
Panel height |
resolution |
number |
300 |
Pixels per world unit |
rotation |
{x,y,z} |
{0,0,0} |
Euler rotation |
billboard |
boolean |
false |
Face camera every frame |
transparent |
boolean |
false |
Render transparent background |
backgroundColor |
string |
#222222 |
Background when not transparent |
onClick |
(href: string) => void |
- | Anchor click callback |
Returns: Promise<pc.Entity | null> (entity includes panel.updateContent(newHtml, options?))
Making your own 3D objects clickable and hoverable. The platform picks by rendering entity ids to a framebuffer, so a hit is mesh-accurate, costs nothing per frame, and needs no collision or rigidbody on the entity. Both events bubble: bind your plugin's host entity and you catch interaction on any of its child meshes.
Don't roll your own. The common mistake is a DOM
mousemovelistener pluscamera.screenToWorld()andrigidbody.raycastFirst(). A physics ray returns the first collider along it, which in a real space is usually the room shell or a splat's collision mesh, not your object — so it works in an empty test room and silently stops working once there is anything in front. It also needs a collider on everything you want to hit, and raycasting per frame is expensive.
Call handler when entity (or a descendant) is clicked. A click is press and release on
the same entity within 500ms and 4px, so dragging to orbit the camera is not a click.
| Param | Type | Description |
|---|---|---|
entity |
pc.Entity |
Entity to listen on (descendants included) |
handler |
(event) => void |
Called on click |
Returns: () => void — unsubscribe. Called automatically if the entity is destroyed.
export class ColorCubes extends ArrivalScript {
static scriptName = "colorCubes";
initialize() {
this._offs = [];
for (const cube of this._buildCubes()) {
const mat = cube.render.meshInstances[0].material;
this._offs.push(ArrivalSpace.onEntityClick(cube, () => {
mat.diffuse = new pc.Color(Math.random(), Math.random(), Math.random());
mat.update();
}));
this._offs.push(ArrivalSpace.onEntityHover(cube, {
enter: () => { mat.emissive = new pc.Color(0.35, 0.35, 0.35); mat.update(); },
leave: () => { mat.emissive = new pc.Color(0, 0, 0); mat.update(); },
}));
}
}
destroy() {
this._offs.forEach((off) => off());
}
}In VR the controller ray clicks and hovers the same entities: while the ray is on an entity with
a click handler, the trigger (or a hand pinch) clicks it and does not teleport the player.
Requires ArrivalSpace.VERSION >= 1.29.0.
event.stopPropagation() makes the mesh solid. Called in the click handler it consumes the
click: it stops reaching the entity's ancestors and the rest of the platform does not react - no NPC
or gate behind the mesh is clicked through it, and the player does not walk to where you clicked.
Without it the handler runs and everything else still happens too (the mesh has no collider, so the
platform's physics side cannot see it). Called in onEntityHover's enter it claims the hover:
nothing behind highlights or shows a pointer cursor. Leave it out only for a pass-through overlay.
ArrivalSpace.onEntityClick(this._button, (e) => { e.stopPropagation(); this.press(); });
ArrivalSpace.onEntityHover(this._button, { enter: (e) => { e.stopPropagation(); this.glow(true); }, leave: () => this.glow(false) });enter fires when the pointer moves onto entity or a descendant, leave when it moves
off. leave also fires if picking is switched off while the entity is hovered, so a
highlight cannot get stuck on.
| Param | Type | Description |
|---|---|---|
entity |
pc.Entity |
Entity to listen on (descendants included) |
handlers.enter |
() => void |
Pointer entered |
handlers.leave |
() => void |
Pointer left |
Returns: () => void — unsubscribe. Called automatically if the entity is destroyed.
Already interactive without this: NPCs take onClick / onHoverEnter / onHoverLeave
in createNPC, and createTexturePanel takes an onClick(href) for anchors in its HTML.
Use these two calls for everything else — your own meshes, loaded GLBs, procedural geometry.
Drag a 3D entity: a press on it, the pointer's moves while it is held, and its release. The press
is picked like onEntityClick (mesh-accurate, no collider). For the length of the drag the
platform's camera stays still — no orbit or look — and the moves are followed anywhere on the page,
also past the canvas's edge. The left button and one finger drag. A press that never moves is still
a drag (start, end), and its click is consumed, so the player does not walk to the knob.
Use it for anything taken in hand and moved: levers, sliders, dials, a crank.
Requires ArrivalSpace.VERSION >= 1.31.0.
| Param | Type | Description |
|---|---|---|
entity |
pc.Entity |
Entity to listen on (descendants included) |
handlers.start |
({x, y}) => void |
Pressed |
handlers.move |
({x, y, dx, dy, startX, startY}) => void |
Moved while held; dx/dy since the last move |
handlers.end |
({x, y}) => void |
Released (or the subscription ended mid-drag) |
Positions are CSS pixels of the canvas, as in mouse events.
Returns: () => void — unsubscribe (ends a drag under way). Called automatically if the entity is destroyed.
// A lever along the screen's vertical: up is more
this._off = ArrivalSpace.onEntityDrag(this._lever, {
start: () => this.setCursor('grabbing'),
move: ({ dy }) => { this._value = pc.math.clamp(this._value - dy / 200, 0, 1); },
end: () => this.setCursor(null),
});To make the knob light up first, pair it with onEntityHover and this.setOutline(knob, on).
Where a world point is on the screen, in CSS pixels of the canvas, as the camera sees it now.
Returns { x, y, inFront, onScreen } (inFront: ahead of the camera — x/y mean nothing
otherwise; onScreen: also inside the canvas), or null without a camera.
Requires ArrivalSpace.VERSION >= 1.31.0.
Prefer it over the engine's camera.worldToScreen(p, out): that one also projects points
behind the camera (mirrored onto the screen), and given the same vector as the point and the
answer it writes the answer before it has finished reading the point — silently wrong.
Call it from onCameraPlaced for positions that must match the frame being drawn.
Draw the platform's silhouette outline on an entity — the same highlight the editor puts
on an object you hover, but switched on when you decide rather than by the pointer. Marks a
quest target, shows what's selected, flashes a hint. Applies to the entity and its descendants
that have a render component.
| Param | Type | Default | Description |
|---|---|---|---|
entity |
pc.Entity | boolean |
this.entity |
What to outline. A boolean here is shorthand for this vibe's own entity — this.setOutline(false) |
on |
boolean |
true |
true to outline, false to clear |
this.setOutline(); // outline my own model
this.setOutline(false); // clear it
this.setOutline(this._target); // outline something else
this.setOutline(this._target, false); // clear thatIdempotent, so calling it every frame from update() is fine.
Prefer this.setOutline(...) over ArrivalSpace.setOutline(...) inside a plugin. The
outline system reference-counts outlined entities and detaches its post-processing pass when
the count reaches zero; an outline left switched on — or an entity destroyed while outlined —
never decrements it, so the pass stays attached for every visitor for the rest of the
session. The instance method tracks what it switched on and clears it when the plugin or the
entity is destroyed. this.clearOutlines() clears them all by hand.
Outline colour and thickness are app-wide, set on the space's camera — a vibe gets the space's outline style, it doesn't choose its own.
Three ways to ask "what is there", with different answers. All skip the local player (its
avatar and capsule) unless includePlayer: true.
raycastScreen(x, y) |
raycastVisual(origin, direction) |
raycastPhysics(origin, direction) |
|
|---|---|---|---|
| Hits | what is drawn at a screen point: splats, every mesh, vibe objects - no collider needed | what is drawn along any 3D ray | colliders only: ground boxes, a space's collision mesh, rigidbodies |
| On a splat | the splat surface the player sees | the splat surface seen from the ray's origin | the collision mesh, or the flat ground box when the space has none |
| A mesh without a collider | hit | hit | passed through - the ray returns the floor behind it |
| Cost | one render into a depth buffer, async (about a frame); calls in the same frame with the same options share it - 81 pixels cost 20-80 ms | a narrow camera renders from the origin, async (about 30-80 ms); rays run one at a time | synchronous, well under a millisecond |
Returns normal |
no - a splat's depth is too grainy per pixel for a surface direction | no | yes, from the collider |
Measured in a splat space whose only collider is a ground box: through the same screen points,
physics hit the box 0.05-0.75 m off the visible gravel, and through a tent wall it returned the
floor 10 m behind it. Along the same rays, raycastScreen and raycastVisual agreed to
0.00-0.23 m.
Splat opacity. A splat is a cloud of semi-transparent Gaussians, and a pick sees through
every single one fainter than minSplatOpacity. Seen from the angles it was captured from, a
surface stacks many Gaussians per pixel and is hit at the engine default 0.3. From other angles
(straight down onto a walk-through filmed at eye level) it is often a blend of faint ones: at
0.3, rays from 0.5 m above the ground missed or landed 0.6 m low at 4 of 9 spots; at 0.1, 8 of
9 were within -0.03..+0.15 m. Dense captures (MCMC training) can be see-through at 0.3 even
from the capture angles: in a forest walk-through, 9 x 9 pixel windows at 0.3 jumped between
the bank 3.5 m away and the wall 16.8 m behind it from pixel to pixel; at 0.1 each window was
one coherent surface. Lower values also make faint floaters in the air count. A value other
than the scene's waits for one more render and applies to splat shadows during it.
The surface the player sees at a screen position. x/y are CSS pixels relative to the
canvas, as in mouse and touch events.
| Option | Type | Default | Description |
|---|---|---|---|
ignore |
pc.Entity[] |
[] |
Entities (with children) to see through, e.g. your own markers |
includePlayer |
boolean |
false |
Hit the local player's avatar too |
resolution |
number |
0.5 |
Fraction of the screen resolution rendered, 0.25..1 |
minSplatOpacity |
number |
scene's (0.3) |
Gaussians fainter than this are seen through, 0.01..1 |
Returns: Promise<{ point: pc.Vec3, distance: number, entity: pc.Entity | null, isSplat: boolean } | null>
nullwhere nothing is drawn (sky) and on very faint splat edges.entityis the hit mesh's entity,nullon a splat.
const hit = await ArrivalSpace.raycastScreen(event.x, event.y, { ignore: [this.marker] });
if (hit) this.marker.setPosition(hit.point);Example: examples/measure-tool.mjs - distances, paths, areas and heights.
Where the color the player sees at a screen position comes from in the gaussian splats (API
1.30.0). x/y are CSS pixels relative to the canvas, as in mouse and touch events.
A splat surface is a layer of faint Gaussians - on dense captures most are fainter than 0.2 - and
along a grazing ray its color builds up over tens of centimeters to meters. raycastScreen takes
the first Gaussian above an opacity, the front of that layer. raycastSplats composites the pixel
the way the renderer does (each Gaussian projected and sorted the same way) and returns the point
where half of the pixel's splat color has built up. Its weighted depth matches the renderer's own
within 2% (median). In a forest walk-through, points re-measured from a camera 1.5 m to the side
moved 35 cm (median) with raycastSplats and 212 cm with raycastScreen at minSplatOpacity: 0.1.
| Option | Type | Default | Description |
|---|---|---|---|
ignore |
pc.Entity[] |
[] |
Splat entities (with children) to see through |
Returns: Promise<{ point: pc.Vec3, distance: number, spread: number, opacity: number, entity: pc.Entity } | null>
pointwhere half the color has built up,distancefrom the camera.spread: the length of ray over which the middle half of the color builds up - centimeters on a crisp surface, meters on foliage or a grazing view.opacity(0..1): how much of the pixel the splats cover; below 1 the rest shows through.nullwhere no splat covers the pixel.
Splats only - meshes, avatars and vibe objects are not part of it (raycastScreen sees them).
SOG splats, LOD and single-file; a splat in another format is not seen. The first call that
reaches a splat, or a LOD level loaded since, reads its data back from the GPU (about 0.2-0.3 s
per million splats); later calls take about 10 ms. Calls made together (in the same tick, with
the same options) share one pass: five neighbouring pixels cost about as much as one.
const hit = await ArrivalSpace.raycastSplats(event.x, event.y);
if (hit) this.marker.setPosition(hit.point);What is drawn along a 3D ray - the visible ground under an object, the line of sight between
two points. origin/direction are {x,y,z} (direction normalized for you), maxDistance
defaults to 50 m. The ray renders through a 5 degree view; where its centre finds nothing, the
median of the hits close around it is used (needs a third of them).
| Option | Type | Default | Description |
|---|---|---|---|
ignore |
pc.Entity[] |
[] |
Entities (with children) to see through, e.g. the object itself |
includePlayer |
boolean |
false |
Hit the local player's avatar too |
minSplatOpacity |
number |
0.1 |
Gaussians fainter than this are seen through, 0.01..1 |
Returns: Promise<{ point: pc.Vec3, distance: number, entity: pc.Entity | null, isSplat: boolean } | null>
// height of the visible ground under a flying object
const hit = await ArrivalSpace.raycastVisual(drone.getPosition(), { x: 0, y: -1, z: 0 }, 30, { ignore: [drone] });
if (hit) label.textContent = `${hit.distance.toFixed(1)} m above ground`;A ray against colliders. origin/direction are {x,y,z} (direction normalized for you),
maxDistance defaults to 100 m. Options: ignore (entities to pass through) and
includePlayer (hit the player's capsule and the free-camera sphere).
Returns: { point: pc.Vec3, normal: pc.Vec3, distance: number, entity: pc.Entity } | null
// keep a ball on the ground every frame
const from = ball.getPosition().clone().add(new pc.Vec3(0, 1, 0));
const hit = ArrivalSpace.raycastPhysics(from, { x: 0, y: -1, z: 0 }, 5);
if (hit) ball.setPosition(hit.point.x, hit.point.y + radius, hit.point.z);Clicks and taps on the ground stop walking the player there; the camera still orbits and the movement keys still work. In VR it also stops the controller trigger / hand pinch from teleporting the player to the floor the ray points at. Several vibes can hold it at once.
Returns: () => void - gives click-to-walk back (safe to call twice). Call it in destroy().
In VR, the right thumbstick stops snap-turning the player (45° per flick), e.g. while it steers
a vehicle the player is seated in. Head tracking still turns the view and movement is unchanged;
the stick's axes stay readable from the controller
(pc.app.xr.input.inputSources[i].gamepad.axes, right stick = axes[2], axes[3]). Several
vibes can hold it at once. Requires ArrivalSpace.VERSION >= 1.22.0.
Returns: () => void - gives snap turning back (safe to call twice). Call it on dismount and in destroy().
// seated: the right stick steers the car
this._releaseTurn = ArrivalSpace.disableXrTurn();
// on dismount / in destroy():
this._releaseTurn?.();In VR, hides the controller models the platform draws at the player's hands, e.g. while the vibe
shows its own hands or tools, or a seated pose puts them in view. The rays, buttons and tracking
keep working. Several vibes can hold it at once. Requires ArrivalSpace.VERSION >= 1.29.0.
Returns: () => void - shows the controllers again (safe to call twice). Call it in destroy().
Hides avatar name tags on this screen only (everyone else still sees theirs). Without an argument:
every name tag - players, NPCs, also ones that join later. With an avatar entity (a player's entity
from ArrivalSpace.net.getPlayers(), an NPC's npc.entity): that avatar's. Several vibes can hold it
at once; a tag comes back when all have released it. Requires ArrivalSpace.VERSION >= 1.35.0.
Returns: () => void - shows the tags again (safe to call twice). Call it in destroy().
this._showNames = ArrivalSpace.hideNameTags();
// in destroy(): this._showNames?.();Safely destroy an entity and optionally its assets/children.
| Option | Type | Default | Description |
|---|---|---|---|
destroyAssets |
boolean |
false |
Destroy referenced assets too |
recursive |
boolean |
true |
Include child entities |
Get all 7 static gates in the current space.
Returns: Array<{ id, entity, index, gateLogic }>
Get one static gate by index (0-6).
Returns: { id, entity, index, gateLogic } | null
await createGate({ link, title, position, rotation }) places a new gate to another space on every
call: link is a space id ("42485456_80s"), title is shown on it, position is world, rotation
Euler degrees. The gate's front faces its local +Z, so a gate at G faces a point P with
y = Math.atan2(P.x - G.x, P.z - G.z) * 180 / Math.PI. Returns { id, entity, persisted }, or null
without a link.
await updateGate(id, { link, title, position, rotation }) relinks, retitles or moves a gate - one from
createGate, one placed in the editor, or a static gate (getStaticGates() ids; link and title only).
await removeGate(id) deletes a placed gate. Both return true once saved.
All three are saved and shown to everyone only when canEditSpace(); otherwise the change exists in
this client until reload. Requires ArrivalSpace.VERSION >= 1.35.0.
Get the current room center asset entity/script.
Returns: { id, entity, centerAsset } | null
Get current room info.
Returns: { roomId, roomName, roomData, owner }
Check whether the current user owns the current space.
Returns: boolean
Check whether the current user can edit the current space — the owner, a site admin, a team or per-space editor, or a seat holder. Decided by the server when the space loads. Plugin-code writes (setParam/setParams/save, createPlugin/reloadPlugin/removePlugin) persist only when this is true. Requires ArrivalSpace.VERSION ≥ 1.16.0.
Returns: boolean
Whether the space editor is open — someone who can edit the space is arranging it, whichever
entity is selected (onEditModeChanged covers only this vibe being selected). Always false for
visitors. Requires ArrivalSpace.VERSION >= 1.29.0.
Returns: boolean
Calls callback(isEditing) each time the space editor opens or closes. Requires
ArrivalSpace.VERSION >= 1.29.0.
Returns: () => void — unsubscribe. Call it in destroy().
this._offEdit = ArrivalSpace.onSpaceEditModeChanged((editing) => { this.marker.enabled = !editing; });
// in destroy(): this._offEdit();List entities in the scene.
Returns: Array<{ name, enabled, pos, children }>
Find an entity by name.
Returns: pc.Entity | null
Find entities by tag.
Returns: pc.Entity[]
Inspect one entity.
Returns: { info, entity } | null
Print scene hierarchy.
Returns: pc.Entity | null
Move an entity.
Returns: boolean
Rotate an entity (Euler degrees).
Returns: boolean
Uniformly scale an entity.
Returns: boolean
Get player CharacterController entity. Use this for the character's position in the world.
Returns: pc.Entity | null
Get the player's avatar mesh entity (ReadyPlayerMe) which has the anim component.
Returns: pc.Entity | null
Move the local player to a world position, optionally setting which way they end up facing. Same path as the platform's own spawn/teleport — no physics sweep between the two points.
| Param | Type | Description |
|---|---|---|
position |
{x,y,z} |
World position |
options.azimuth |
number |
Heading in degrees. 0° faces −Z, 90° faces −X — the same convention as a spawn point's rotation.y (see room-config.md) |
options.forward |
{x,y,z} |
Heading as a direction vector instead (Y ignored, normalised for you) |
options.elevation |
number |
Camera pitch in degrees, + looks up, clamped to −80…70 (API 1.19.0) |
Returns: boolean — false if there is no local player or the position isn't finite.
Pass one of azimuth or forward; both set the first/third-person look direction. Without
either, the player keeps their current heading, which is why a plugin that teleports someone
to face a painting or down a corridor has to say so explicitly.
Raises or lowers the floor the player walks on where the space has no floor of its own — a splat
or map world, where the player stands on an invisible ground at height 0. height is a world Y in
metres, or a function (x, z) => y that is asked under the player every frame, so the floor follows
terrain your plugin knows (a heightmap, the ground of a 3D map) as the player walks. null puts it
back at 0. A space with its own floor collision is not changed. One at a time: the last call wins.
A function that throws or returns a non-number counts as 0 there. Requires
ArrivalSpace.VERSION >= 1.34.0.
Returns: () => void — release: the floor back at 0, unless another call has replaced this
one since. Call it in destroy().
initialize() {
this._releaseGround = ArrivalSpace.setGroundHeight?.((x, z) => this.terrainHeight(x, z));
}
destroy() {
this._releaseGround?.();
}Runs callback once the space has finished loading - its entities, models and splats are in,
at full detail, and the loading screen is gone - or on the next tick when it already has. A vibe
starts while its space is still loading: this is where to raycast the ground, place things on
loaded models or splats, or hide a loading overlay of its own. A load replaced by a space switch
never calls it. Requires ArrivalSpace.VERSION >= 1.37.0.
Returns: () => void — cancels the callback if it has not run yet; call it in destroy().
initialize() {
this._offLoaded = ArrivalSpace.onSpaceLoaded(() => this._dropOnGround());
}
destroy() {
this._offLoaded();
}getSpaceContent() lists the space's content as the editor's Content panel does: every entity as
{ id, type, name, folderId, data } (type UserModelEntity, CustomSoundEntity, AnnotationEntity,
SpawnPoint, DynamicGate, ...; name as the panel shows it; data its saved data, a vibe's params under
data.params); getEntity(id) is its scene entity. getContentFolders() lists the folders,
{ id, name, parentId, hidden, order }; an entity's folderId is its folder, and a hidden folder hides
everything in it and its sub-folders.
getSounds() returns the sound entities to control from a vibe: { id, name, url, folderId, playing, play(), pause(), stop(), setVolume(volume) }. A sound plays while the visitor is within its
data.distance and pauses outside, unless its data.autoplay is false ("Play when in range" off in
the editor): then only play() starts it. play / pause / stop take it out of that range control
for this visit; they and setVolume act in this client only. Requires ArrivalSpace.VERSION >= 1.37.0.
// every track of one content folder at once
const folder = ArrivalSpace.getContentFolders().find((f) => f.name === "Soundtrack");
for (const s of ArrivalSpace.getSounds().filter((s) => s.folderId === folder.id)) s.play();getAnnotations() returns the annotations (the editor's info markers): { id, text, position, folderId, entity, isOpen, open(), close() }. text is what the popup shows, one line per paragraph; open /
close show or hide the popup in this client only, as a visitor's click on the marker does; entity
is the marker, for onEntityClick / onEntityHover. Requires ArrivalSpace.VERSION >= 1.37.0.
// open each annotation while the pointer is over its marker
for (const a of ArrivalSpace.getAnnotations()) ArrivalSpace.onEntityHover(a.entity, { enter: a.open, leave: a.close });An annotation is an AnnotationEntity entity; its data:
| Key | Value |
|---|---|
position |
{ x, y, z } |
editState |
The content: a Lexical editor state as a JSON string (below). The popup shows this. |
htmlString |
The same content as HTML; its text is the annotation's name in the Content panel |
alwaysOpen |
true: the popup stays open |
openByDistance, triggerDistance |
Opens while the player is within triggerDistance m (default 5) |
uiAnchor |
Popup side: "top", "bottom" (default), "left", "right" |
icon, iconBackground |
Emoji or text (≤ 8 characters) in place of the 3D marker; a background behind it |
hideButton |
No marker: the content shows through alwaysOpen / openByDistance only |
fixedScreenSize |
The marker keeps its size on screen at any distance |
backgroundColor, textColor |
"#rrggbb" |
hidden, folderId |
As for any content |
editState, one paragraph per line; a text node's format is a bit mask: 1 bold, 2 italic, 8 underline:
{"root":{"type":"root","version":1,"children":[
{"type":"paragraph","version":1,"children":[{"type":"text","version":1,"text":"Shelf A","format":1}]},
{"type":"paragraph","version":1,"children":[{"type":"text","version":1,"text":"Tools and spare parts"}]}
]}}A screen-share gate is a DynamicGate with data.dynamicGate.screenShare: true (screenShareVisitors: true
lets any visitor take it, otherwise only people who can edit the space). getScreenShares() returns the
shares live on those gates, one per sharer and kind, the local player's own included:
{ gateId, kind: "screen" | "camera", userName, socketId, isLocal, stream }. stream is the share's video
as a MediaStream, for a vibe's own <video> - a 2D panel at the edge of the screen, a row of call-style
tiles. The gate keeps showing the share and keeps playing its sound (at the gate's position unless
dynamicGate.screenShareSpatialAudio is false, then plainly for everyone), so the vibe's element is muted.
socketId matches ArrivalSpace.net.getPlayers(). onScreenSharesChanged(cb) calls cb(shares) whenever
a share starts, ends, moves to another gate or gets a new stream (sometimes without a change) and returns
the unsubscribe.
await startScreenShare(gateId, "screen" | "camera") shares the local player's screen or camera to a
screen-share gate, as clicking the gate does: the browser asks for the screen or the camera, so call it
from a click. It resolves true once the share is live, false when it was refused (the gate is taken or
host-only, no voice connection - said on screen), cancelled in the browser's picker, or gateId is no
screen-share gate. One share per gate; a new share of a kind ends this player's previous one of that kind.
stopScreenShare(kind) ends one, stopScreenShare() all of them. Requires ArrivalSpace.VERSION >= 1.39.0.
// pin every share to the right edge of the screen
this._panel = this.createUI("div", { style: { position: "fixed", top: "80px", right: "16px", width: "320px",
display: "flex", flexDirection: "column", gap: "8px", zIndex: "1000" } });
const show = (shares) => {
this._panel.replaceChildren(...shares.map((s) => {
const v = document.createElement("video");
Object.assign(v, { muted: true, autoplay: true, playsInline: true, srcObject: s.stream });
v.style.cssText = "width:100%;border-radius:8px;background:#000";
return v;
}));
};
this._offShares = ArrivalSpace.onScreenSharesChanged(show);
show(ArrivalSpace.getScreenShares());
// destroy(): this._offShares(); this.removeUI();Where a player lands entering the space without a gate: the spawn point marked as default,
else the scene's start position. Read at call time, so it follows the owner moving the spawn
point. Requires ArrivalSpace.VERSION >= 1.29.0.
Returns: { position: {x,y,z}, forward: {x,y,z} } | null — forward is the horizontal
direction the player faces there; both fit teleportPlayer. null before the space has loaded.
Add, change or remove a spawn point, where visitors appear entering the space (getDefaultSpawnPoint()
is the default one). The options are a SpawnPoint entity's data: position on the ground (the
avatar's feet), rotation { x: pitch, y: yaw, z: 0 } in degrees (yaw 0 faces -Z),
isDefaultThirdPerson / isDefaultFreeCam (one spawn point holds each role: true takes it from the
others; left out, a new one takes a role nobody holds), alwaysSnapBack, hidden (skipped when
choosing where to spawn), displayName. Saved and used for everyone only when canEditSpace();
otherwise in this client until reload. Requires ArrivalSpace.VERSION >= 1.37.0.
Returns: createSpawnPoint → Promise<{ id, entity, persisted } | null> (null without a position);
updateSpawnPoint / removeSpawnPoint → Promise<boolean>, true once saved.
const p = ArrivalSpace.getPlayer().getPosition();
await ArrivalSpace.createSpawnPoint({ position: { x: p.x, y: p.y, z: p.z }, isDefaultThirdPerson: true });Teleports the local player to getDefaultSpawnPoint(), facing its direction. Requires
ArrivalSpace.VERSION >= 1.29.0.
Returns: boolean — false before the space has loaded or without a local player.
// Face down −Z at the destination
ArrivalSpace.teleportPlayer({ x: 0, y: 1, z: 5 }, { azimuth: 0 });
// Or aim at a target entity
const to = target.getPosition().clone().sub(ArrivalSpace.getPlayer().getPosition());
ArrivalSpace.teleportPlayer({ x: 0, y: 1, z: 5 }, { forward: { x: to.x, y: 0, z: to.z } });Heading is ignored while an XR session is active — the headset owns the view direction. There is no supported way to turn the player smoothly to a heading without teleporting; this sets it instantly, as part of the jump.
Set the local player's world-space velocity in metres per second. Accepts { x?, y?, z? }
or a pc.Vec3; at least one finite numeric axis is required. Omitted/undefined axes are
preserved; 0 stops an axis. 14.0).
ArrivalSpace.setPlayerVelocity({ y: 10 }); // Preserve X/Z.Returns: boolean. false without changes for invalid input, an unavailable or suspended
player, disabled controller/rigidbody/collision, non-dynamic rigidbody, paused world, or active
sequence editor.
Set / get the physics world gravity (default { x: 0, y: -9.81, z: 0 }). A bare number sets only
the vertical component. Affects every dynamic body, the player included — restore it in
destroy(). Requires ArrivalSpace.VERSION ≥ 1.15.0.
ArrivalSpace.setGravity(-1.62); // MoonScale the player's jump impulse (1 = the room's default; same knob as the room setting).
Requires ArrivalSpace.VERSION ≥ 1.15.0.
This sets velocity once. Gravity, collisions and player input continue afterward; steering can change X/Z on the next movement update. Upward motion releases ground support and prevents ground damping during takeoff. Normal ground handling resumes on descent.
See Velocity Pad.
Get the local player's current movement input intent. Works on desktop (W/S/A/D, arrow keys) and mobile (virtual joystick) — sourced from the same input pipeline the character controller uses, so plugins do not need to poll the keyboard or getLeftStick() separately.
Gamepads (browser standard mapping, e.g. PS5 / Xbox controllers): the platform uses the left stick to walk, the right stick to look and the bottom face button (Cross / A) to jump. No other button is used by the platform; a plugin can read them in update() with navigator.getGamepads() (gamepad.buttons[i].pressed, standard button order). Rumble is the browser API too: gamepad.vibrationActuator?.playEffect('dual-rumble', { duration: 200, strongMagnitude: 1, weakMagnitude: 0.5 }) (Chromium browsers; other browsers and some pads have no vibrationActuator). One controller can be listed more than once, so rumble every connected pad.
Returns: { forward: number, strafe: number, jump: boolean }
| Field | Range | Meaning |
|---|---|---|
forward |
-1..+1 |
> 0 = forward (W / up / joystick up), < 0 = back (S / down / joystick down) |
strafe |
-1..+1 |
> 0 = right (D / joystick right), < 0 = left (A / joystick left) |
jump |
boolean |
true while the jump action is held |
update(dt) {
const move = this.getMoveInput();
if (move.forward > 0.1) {
// Player wants to walk forward — react however you like.
}
}Set the global physics simulation step rate for the current world.
This affects the shared physics world, so if multiple plugins call it, the latest call wins.
| Param | Type | Description |
|---|---|---|
stepHz |
number |
Physics tick rate in Hz (for example 60, 120, 180) |
maxSubSteps |
number |
Maximum Bullet substeps per frame; never below stepHz (one second of steps), so physics keeps real time down to 1 fps |
Returns: boolean
// Use the default engine stepping
ArrivalSpace.setPhysicsStepRate(60, 10);
// Increase stability for demanding physics interactions
ArrivalSpace.setPhysicsStepRate(120, 10);Apply a visual local offset to the local player's avatar mesh without affecting physics.
Pass 0, 0, 0 to reset the offset.
Returns: boolean
Get the entity the local player is currently standing on.
Returns: pc.Entity | null
Subscribe to standing-object changes.
Callback: (currentEntity, previousEntity) => {}
Returns: Function unsubscribe function
Subscribe once to the next standing-object change.
Returns: Function unsubscribe function
Remove a standing-object change listener.
Get camera entity. Use this for the player's viewing direction (heading/yaw).
Returns: pc.Entity | null
3rd-person note: The camera orbits the player character, so
getCamera().getPosition()is NOT the character's position. UsegetPlayer()for position andgetCamera()for heading.
Switch the camera mode.
| Param | Type | Description |
|---|---|---|
mode |
"free" | "third" | "first" | "orbital" |
Camera mode to switch to |
Returns: boolean — true if the mode was set
ArrivalSpace.setCameraMode("free");
ArrivalSpace.setCameraMode("third");Get the current camera mode.
Returns: "free" | "third" | "first" | "orbital" | null
Position the free camera and optionally aim it at a target. Switches to free cam mode first if it is not already active. The horizon is kept level (roll = 0). (VERSION ≥ 1.11.0)
| Param | Type | Description |
|---|---|---|
position |
pc.Vec3 | {x, y, z} |
World position for the camera |
lookAt |
pc.Vec3 | {x, y, z} |
Optional world position to aim at |
Returns: boolean — true if the pose was applied
// Jump the free cam to a viewpoint framing an entity
const target = entity.getPosition();
ArrivalSpace.setFreeCamPose({ x: target.x + 4, y: target.y + 2, z: target.z + 4 }, target);Set the free camera's movement speed and/or raise its maximum. The scroll-wheel speed adjustment clamps to the max (default 50 m/s, good for room-scale spaces) — raise it for large streamed worlds, e.g. flying across a Google 3D Tiles city. Requires free cam mode to be active. (VERSION ≥ 1.11.2)
| Param | Type | Description |
|---|---|---|
speed |
number | null |
New current speed in m/s, or null to leave the current speed unchanged |
maxSpeed |
number |
Optional new maximum for the scroll-wheel speed clamp |
Returns: boolean — true if applied, false if the free cam is not available
ArrivalSpace.setCameraMode("free");
ArrivalSpace.setFreeCamSpeed(200, 2000); // fly at 200 m/s, scroll up to 2 km/s
ArrivalSpace.setFreeCamSpeed(null, 2000); // only raise the capGet the free camera's current movement speed and maximum. Lets plugins that drive the speed (e.g. altitude-proportional flying) detect the user's scroll-wheel adjustments instead of stomping them. (VERSION ≥ 1.11.2)
Returns: { speed, maxSpeed } | null — null if the free cam is not available (not in free cam mode yet)
const info = ArrivalSpace.getFreeCamSpeed();
if (info) console.log(`flying at ${info.speed} m/s (max ${info.maxSpeed})`);Get current user profile summary.
Returns: { userID, userName, uniqueName, avatar, isRegistered }
isRegistered is false for a guest (no sign-in); a guest's userID belongs to that temporary account only. API 1.18.0.
Capture current camera view and upload screenshot.
Defaults: width=1024, height=768
Returns: Promise<{ success: boolean, url?: string, error?: string }>
Replace a character animation by loading a GLB and assigning it to an animation state. Pass null as the URL to reset to the default animation.
By default, root bone XZ translation is stripped so animations play in place (the character doesn't drift). This is usually what you want since movement is handled by the engine. Pass { inPlace: false } to keep the original root motion.
| Param | Type | Description |
|---|---|---|
state |
string |
Animation state to replace |
url |
string | null |
GLB URL with the animation, or null to reset |
options.inPlace |
boolean |
Strip root bone XZ movement (default: true) |
options.startTime |
number |
Start the animation at this time offset in seconds (default: 0) |
State names: "Idle", "Forward" (walk), "Jumping", "Signature1" through "Signature4"
Returns: Promise<boolean>
// Replace walk animation (root motion stripped automatically)
await ArrivalSpace.setPlayerAnimation('Forward', 'https://example.com/zombie_walk.glb');
// Keep root motion (character will drift with the animation)
await ArrivalSpace.setPlayerAnimation('Forward', url, { inPlace: false });
// Start an emote part-way through the clip
await ArrivalSpace.setPlayerAnimation('Signature1', url, { startTime: 1.25 });
// Reset to default
await ArrivalSpace.setPlayerAnimation('Forward', null);By default, movement speed and walk animation speed are coupled — slowing down movement also slows the animation proportionally (e.g. walking through mud). Use setPlayerAnimSpeed when you need independent control over animation playback (e.g. a custom animation that has a different natural cadence).
Set the character movement speed multiplier. Affects both physics movement and walk animation speed proportionally — unless setPlayerAnimSpeed has been called for that state, in which case animation speed is decoupled.
| Param | Type | Description |
|---|---|---|
multiplier |
number |
Speed multiplier (0.8 = default, the room's moveSpeed when unset) |
// Slow everything down (movement + animation) — e.g. mud, slugs
ArrivalSpace.setPlayerSpeed(0.3);
// Reset
ArrivalSpace.setPlayerSpeed(1);Set the animation playback speed for a specific state, decoupled from movement speed. Once set, the state's animation speed is no longer affected by setPlayerSpeed — the override is absolute. Pass null to remove the override and re-couple with movement speed.
| Param | Type | Description |
|---|---|---|
state |
string |
"Idle", "Forward", or "Jumping" |
speed |
number | null |
Playback speed (1.0 = normal, 0 = frozen, 2.0 = double), or null to remove override |
// Freeze idle pose (e.g. custom idle animation as a static pose)
ArrivalSpace.setPlayerAnimSpeed('Idle', 0);
// Custom walk animation plays at normal speed, independent of moveSpeed
ArrivalSpace.setPlayerAnimSpeed('Forward', 1.0);
// Remove override — re-couples with setPlayerSpeed
ArrivalSpace.setPlayerAnimSpeed('Forward', null);Create a controllable NPC with avatar, animation, and optional interaction helpers.
Supports:
- spawn/transform options (
position,rotation,scale,parent).scaleis the NPC root's scale, default1. The avatar inside is already shown at the space'sworldScalelike the player's, so1is a normal-size human; don't multiply byworldScaleagain. - avatar setup (
avatarUrl,avatarConfig,avatarParts,avatarGender) —avatarConfig: { type: 'vrm', url }takes an uploaded VRM avatar or any.vrmfile URL (VRM 0 or 1); its humanoid rig comes from the file, and a raw.vrmidles and walks with the catalog'sidle/walkingclips untilanimationsorsetAnimationgive it others - movement tuning (
speed,turnSpeed,stopDistance) - optional custom animation refs (
animations.idle,animations.walk,animations.jump) — each accepts a catalog/GLB clip or a raw Mixamo.fbxURL, which the platform converts to a generic clip on the fly and retargets onto the avatar (VRM and modular/RPM); no pre-conversion needed - optional interaction callbacks (
onClick,onHoverEnter,onHoverLeave)
Interaction behavior:
- Set
onClickto add click functionality to the NPC. onHoverEnterandonHoverLeavecan be used for custom hover reactions.
Returns: Promise<npcController>
Common controller methods:
npc.walkTo(target, options?)npc.stop()npc.lookAt(target)npc.setAnimation(state, animationRef, options?)—animationRefis a catalog/GLB clip or a raw Mixamo.fbxURL (auto-converted and retargeted)npc.setActivity(name)— a looping clip from the avatar's own set:'talking'(hand gestures),'listening','thinking','waving', ornullfor idle. Walking andplayOncepause it. RequiresArrivalSpace.VERSION >= 1.25.0.npc.playOnce(animationRef)— plays a clip once (a catalog key such as'quick_formal_bow.glb','salute.glb','waving.glb', or a GLB / Mixamo.fbxURL); resolvestruewhen it finished,falsewhen anotherplayOncereplaced it or the NPC was destroyed. 1.25.0.npc.setLookTarget(target, { height, turnBody = true }?)— the head and neck keep turning to a point or an entity, on top of whatever clip plays: up to 70° sideways and 30° up or down; past 45° the body turns after it. An avatar (the player fromArrivalSpace.getPlayer(), another NPC) is looked in the eyes; other entities atheight(default 1.5) above their origin.nulllooks straight ahead again. 1.25.0.npc.applyAvatarConfig(config, renderOptions?)npc.setAvatarParts(parts, options?)npc.setSpeed(value),npc.setTurnSpeed(value),npc.setStopDistance(value)npc.getState()npc.destroy()
Avatars are built from modular parts. Each part belongs to a category and is identified by its part ID (a GLB filename from the catalog).
Catalog files (JSON with every part ID, thumbnail URL, and description per category):
- Male:
https://ugc.arrival.space/avatar-parts/catalog.json - Female:
https://ugc.arrival.space/avatar-parts-female/catalog.json
| Category | Description | Notes |
|---|---|---|
body |
Body build/shape | |
head |
Face | |
teeth |
Teeth mesh | |
eyeLeft |
Left eye | |
eyeRight |
Right eye | |
hair |
Hair style | Auto-removed when headwear is set |
glasses |
Eyewear | |
headwear |
Hats, helmets, headgear | Auto-removes hair when set |
facewear |
Masks, scarves, etc. | |
top |
Upper body clothing | |
bottom |
Lower body clothing | |
footwear |
Shoes/boots |
Part IDs look like "headwear-5.glb", "hair-12.glb", etc. Use getAvatarCatalog() to browse all available parts, their IDs, and thumbnail URLs.
Fetch the full parts catalog. Cached after first call.
| Param | Type | Default | Description |
|---|---|---|---|
gender |
string |
"male" |
"male" or "female" |
Returns: Promise<{ baseUrl: string, categories: Object } | null>
Each category contains a parts array with { id, name, glbUrl, thumbnailUrl, appearance }.
const catalog = await ArrivalSpace.getAvatarCatalog();
const helmets = catalog.categories.headwear.parts;
console.log(helmets.map(h => h.id)); // ["headwear-1.glb", "headwear-2.glb", ...]Fetch available avatar animation keys (for example walking.glb, shooter/rifle_run.glb).
| Param | Type | Default | Description |
|---|---|---|---|
gender |
string |
"male" |
"male" or "female" |
Returns: Promise<string[] | null>
Get the current avatar's parts configuration (parts map, tints, gender). Returns null if the avatar is not a modular parts-based avatar.
Returns: Promise<{ parts: Object, tints: Object, gender: string } | null>
const config = await ArrivalSpace.getAvatarConfig();
// { parts: { body: "C87448.glb", head: "male-face-1.glb", ... },
// tints: { skinColor: "C87448", hairColor: "2C1810" },
// gender: "male" }Change one or more avatar parts and re-render. Changes are temporary (visual only, not saved to the user's profile) and local: other players keep seeing the saved avatar. Set a part to null to remove it.
| Param | Type | Description |
|---|---|---|
partsToSet |
Object |
Map of category to part ID |
options.tints |
Object |
Override tint colors ({ skinColor, hairColor }) |
options.gender |
string |
Override gender for part resolution |
Returns: Promise<{ ok: boolean, error?: string }>
// Put on a helmet
await ArrivalSpace.setAvatarParts({ headwear: 'headwear-5.glb' });
// Change outfit
await ArrivalSpace.setAvatarParts({ top: 'top-12.glb', bottom: 'bottom-3.glb' });
// Remove headwear
await ArrivalSpace.setAvatarParts({ headwear: null });Show the local player as the avatar file at url — to everyone in the space, players who join later included — until resetAvatar(), a space switch, or a change of the saved avatar. Not saved to the visitor's profile. Requires ArrivalSpace.VERSION >= 1.32.0.
The file is a whole avatar, not a part added to the current one:
- a
.glbwith the platform's humanoid rig (modular-avatar bone names; Mixamomixamorig:names are mapped) plays the stock animations; other bone names load but don't animate; - a URL ending in
.vrmloads as a VRM.
ArrivalSpace.fs.url() URLs carry no extension, so they always load as .glb; a VRM needs its extension (e.g. getPluginFileURL("knight.vrm")). If the file doesn't load, the saved avatar comes back.
Returns: Promise<boolean> — false if the file did not load.
// A clickable disguise: wear the rigged GLB this vibe ships in space/assets/
ArrivalSpace.onEntityClick(this.entity, () =>
ArrivalSpace.setPlayerAvatar(ArrivalSpace.fs.url("assets/knight.glb")));Reset the avatar to the user's saved state. Use this in destroy() to cleanly undo all temporary avatar changes (restores hair, original outfit, etc.). After setPlayerAvatar the other players see the saved avatar again too.
Returns: Promise<boolean>
// In plugin destroy — restores the user's original avatar
async destroy() {
await ArrivalSpace.resetAvatar();
}Show or hide the app's built-in UI (HUD, overlays, name tags, etc.). Useful for immersive experiences that want a clean viewport. Same as pressing the H key.
| Param | Type | Description |
|---|---|---|
visible |
boolean |
true to show, false to hide |
// Hide app UI for immersive mode
ArrivalSpace.setAppUIVisible(false);
// Restore on destroy
ArrivalSpace.setAppUIVisible(true);Two ways to change the space's look:
- Save it with
ArrivalSpace.setRoomSettings()— a vibe that sets up its space (the lighting it was made for, a hidden skybox) writes the space's own settings, so the settings panel shows what's in effect and the owner can tune it there. Prefer this for anything meant to stay. - Override it while the plugin runs with
setPostEffects()/setSkyboxHidden()— nothing is saved, the room's settings come back when the plugin restores them (do it indestroy()). For effects that come and go (a flash, a dream sequence, a volume you walk into).
Change and save the space's own settings — what its settings panel edits; the keys of
ArrivalSpace.getRoom().roomData (e.g. skyboxHidden, skyboxIntensity, stageLightType,
stageLightIntensity, framePosteffectParams, …). Applied at once, stored with the space, shown in
the panel. framePosteffectParams is merged (only the keys given change). Values already stored
aren't written again. roomPrivacy can't be set here.
Only for a user who can edit the space (canEditSpace()); for
everyone else (and in the agent's inspector browser) nothing changes and it resolves false — so
call it where an editor sets the space up (an onInstall, a setup panel's OK), not for every
visitor. Requires ArrivalSpace.VERSION ≥ 1.27.0.
Returns: Promise<boolean> — true once saved (or already so).
// a setup panel's OK: the look this vibe was made for, kept by the space
if (ArrivalSpace.canEditSpace() && ArrivalSpace.setRoomSettings) {
await ArrivalSpace.setRoomSettings({
skyboxHidden: true,
framePosteffectParams: { hdrEnabled: true, toneMapping: 3, bloomEnabled: true, bloomIntensity: 0.14 },
});
}Override post-effect parameters; only the keys given change, the rest keep the room's values.
getPostEffects() returns the current ones (keep a copy to restore later).
| Key | Type | |
|---|---|---|
hdrEnabled |
boolean |
the HDR pipeline (needed for SSAO) |
toneMapping |
number |
0–4 (3: ACES) |
saturation, contrast, brightness, sharpness, gamma |
number |
|
bloomEnabled, bloomIntensity, bloomThreshold, bloomBlurLevel |
bloom | |
ssaoType |
"none" | "lighting" | "combine" |
ambient occlusion (HDR only) |
ssaoIntensity, ssaoRadius, ssaoPower, ssaoSamples, ssaoBlur |
initialize() {
this._roomLook = ArrivalSpace.getPostEffects();
ArrivalSpace.setPostEffects({ hdrEnabled: true, toneMapping: 3, bloomEnabled: true, bloomIntensity: 0.14 });
}
destroy() {
if (this._roomLook) ArrivalSpace.setPostEffects(this._roomLook);
}ArrivalSpace.setSkyboxHidden(hidden) / ArrivalSpace.getSkyboxHidden()
Hide or show the skybox's backdrop — the sky image still lights the scene, as with the room's
own "Hide Skybox". true hides, false shows, null returns to the room's setting (do that in
destroy()). getSkyboxHidden() is the current state. Requires ArrivalSpace.VERSION ≥ 1.27.0.
ArrivalSpace.setSkyboxHidden?.(true); // e.g. a plugin that draws its own sky
// ...
ArrivalSpace.setSkyboxHidden?.(null); // the room's own setting againFor local volume-like effects (see examples/post-process-volume.mjs), plugins can use:
this.app.customTravelCenter.updatePostEffects(params)
Typical params keys:
toneMappingsaturationcontrastbrightnesssharpnessbloomEnabledbloomIntensitybloomThresholdbloomBlurLevelgamma
Load a space by full URL or shorthand (username/path). Query params of the URL (other than
gate) end up in the destination's URL, so its vibes can read them from location.search,
e.g. loadSpace("https://arrival.space/12345678_1234?color=red") (API 1.19.0).
await ArrivalSpace.loadSpace("johndoe");
await ArrivalSpace.loadSpace("https://live.arrival.space/johndoe/gallery");Returns: Promise<any>
Load a user's home space by user ID.
Returns: Promise<any>
Reload the currently loaded space.
Returns: Promise<any>
Create a new space and optionally load it.
| Option | Type | Default | Description |
|---|---|---|---|
title |
string |
'Untitled' |
Space title |
description |
string |
'' |
Space description |
privacy |
'Open' | 'Closed' | 'Link Only' |
'Closed' |
Privacy mode |
environment |
'hub' | 'gallery' |
'hub' |
Hub uses full architecture, gallery uses minimal setup |
loadAfterCreate |
boolean |
true |
Auto-load newly created space |
Returns: Promise<{ success: boolean, roomId?: string, roomName?: string, title?: string, error?: string }>
List spaces for current user or a target user.
Returns: Promise<Array<{ id: string, title: string, privacy: string }>>
List currently loaded plugins in the room.
Returns: Array<{ id: string, url: string, entity: pc.Entity, name: string }>
Upload code, create plugin entity, and load it.
| Option | Type | Default | Description |
|---|---|---|---|
name |
string |
auto | Plugin name/file stem |
position |
{x,y,z} |
{0,0,0} |
Spawn position |
rotation |
{x,y,z} |
{0,0,0} |
Spawn rotation |
scale |
number |
1 |
Uniform scale |
persist |
boolean |
true |
Save plugin entity to server |
Returns: Promise<{ success: boolean, entity?: pc.Entity, id?: string, url?: string, name?: string, error?: string }>
Remove plugin entity from current space and optionally delete from server.
Default: deleteFromServer=true
Returns: Promise<boolean>
Hot-reload a plugin with new code while preserving the same plugin entity.
Returns: Promise<{ success: boolean, id?: string, url?: string, error?: string }>
Requires ArrivalSpace.VERSION ≥ 1.17.0.
ArrivalSpace.fs works like Node's fs/promises, scoped to the current space. Every vibe in the
space sees the same files; folders are just path prefixes (they appear with their first file, so
mkdir is a no-op). Use it for documents a vibe creates or edits at runtime — a level or course
layout, quiz questions, a gallery's images, a visitor's saved game. Keep editor parameters
(setParam) for small settings.
Who can write
- Everyone can read every file of the space.
- Users who can edit the space (
ArrivalSpace.canEditSpace()) can write anywhere. - Logged-in visitors can write only inside their own folder,
ArrivalSpace.fs.homedir()(visitors/<userId>), and only when the space allows it:allowVisitorFiles: truein the room settings (space/room.jsondata). Guests can't write. - Anything else rejects with
EACCES.
Keep the two apart: data editors build for everyone (the course) goes in the space root, e.g.
golf/course.json; data that belongs to one visitor (their scorecard) goes in fs.homedir().
const fs = ArrivalSpace.fs;
// Editor data: read with a default when nothing was saved yet
async function loadCourse() {
try {
return JSON.parse(await fs.readFile('golf/course.json', 'utf8'));
} catch (e) {
if (e.code === 'ENOENT') return { holes: [] };
throw e;
}
}
if (ArrivalSpace.canEditSpace()) await fs.writeFile('golf/course.json', JSON.stringify(course));
// Visitor data: their own folder
await fs.writeFile(`${fs.homedir()}/golf-score.json`, JSON.stringify({ strokes: [3, 4, 2] }));
// Everyone's visitor files
for (const id of await fs.readdir('visitors').catch(() => [])) { /* visitors/<id>/golf-score.json */ }
// Binary files and URLs
await fs.writeFile('gallery/1.png', blob);
img.src = await fs.url('gallery/1.png');
// React to saves by anyone (other clients within ~10 s, this client immediately)
const watcher = fs.watch('golf/course.json', () => reloadCourse());
// in destroy(): watcher.close();| Method | Notes |
|---|---|
readFile(path, encoding?) |
'utf8' → string, 'base64' → string, none → Uint8Array. |
writeFile(path, data, options?) |
data: string, Uint8Array, ArrayBuffer or Blob (objects: JSON.stringify first). Replaces the file. { ifVersion } rejects with ECONFLICT when someone saved in between (version comes from stat). |
appendFile(path, data) |
Read + write. |
readdir(path, { withFileTypes?, recursive? }) |
'' is the space root. |
stat(path) / access(path) |
stat: size, mtime, version, isFile(), isDirectory(). |
unlink(path), rm(path, { recursive?, force? }), rmdir |
Folders need recursive. |
copyFile(src, dest), rename(old, new) |
Files only. |
mkdir(path) |
No-op. |
watch(path, listener) |
listener(eventType, filename), returns { close() }. A folder path watches everything below it. |
url(path) |
Async. CDN URL of the current version, for <img src>, loaders, fetch. Not in Node. |
homedir() |
Sync. visitors/<userId>, like os.homedir(). |
Errors carry Node's codes: ENOENT, EACCES, EISDIR, ENOTDIR, ENOTEMPTY, EINVAL (bad
path or file type), EFBIG, EDQUOT, EAGAIN (too many writes, retry later), ECONFLICT.
Limits
- File types:
.json .txt .csv .md .bin, images (.png .jpg .jpeg .webp .gif .ktx2), audio/video (.mp3 .ogg .wav .m4a .mp4 .webm), 3D (.glb .gltf .ply .splat .sog .spz) and.pdf. Never scripts or HTML (.js .mjs .html .svg, …). - Paths: letters, digits,
. _ -and spaces; no..; up to 255 characters. - Editors: 5 MB per file, 1000 files per space; 120 writes per minute and 2000 per hour per space, all editors together.
- Visitors: 1 MB per file, 20 MB and 100 files each; 10 writes per minute and 100 per hour each, 120 per minute for all visitors together.
- Everything counts toward the space owner's storage.
- Duplicating a space copies its files, except
visitors/. - Reads are public: every visitor, logged in or not, can
readFile,readdirandurlevery file of the space — data a vibe shows to visitors needs no copy in params. Don't store secrets. - Shared lists many visitors add to (scores, votes, a leaderboard) fit
ArrivalSpace.pluginStorebetter:get(key, { sort, limit })returns the top entries in one request, while reading every visitor's file costs one fetch per visitor.
See examples/pin-board.mjs.
Plugin file helpers use plugins/<fileName> under user storage.
Save file content under current user's plugin folder.
Default MIME type: 'application/json'
Returns: Promise<string | false> (URL or false)
Load plugin file from current user or another user.
Returns: Promise<Response | false>
Delete plugin file from current user's plugin folder.
Returns: Promise<boolean>
Get public URL for plugin file.
Returns: string | false
A small shared store per space for lists that many visitors add to — best times, votes, high scores. Any logged-in visitor can write; everyone in the space reads the same entries.
- Values are strings up to 1024 characters (stringify objects yourself); keys up to 64.
numvalis a number the server sorts by, so a leaderboard is onegetcall.- Each entry belongs to the user who wrote it;
deleteremoves only your own entry.
| Option | Type | Description |
|---|---|---|
numval |
number? |
Sort value (score, time, …) |
mode |
"unique" (default) |
"min" |
spaceId |
string? |
Another space (defaults to the current one) |
Returns: Promise<object | false>
| Option | Type | Description |
|---|---|---|
sort |
"asc" (default) |
"desc" |
limit |
number? |
Default 10, max 100 |
prefix |
boolean? |
Match every key starting with key |
spaceId |
string? |
Another space |
Returns: Promise<Array<{ userId, pkey, value, numval, updatedAt }> | false>
Delete your own entry for key. Returns: Promise<boolean>
// Best time per player, top 10 fastest
await ArrivalSpace.pluginStore.push('best-time', ArrivalSpace.getUser().userName, { numval: 12.3, mode: 'min' });
const board = await ArrivalSpace.pluginStore.get('best-time', { sort: 'asc', limit: 10 });See examples/scavenger-hunt-leaderboard.mjs.
Per-user persistent key-value storage that works across spaces. Data is
scoped by a namespace string — typically the plugin author's own space ID.
Only code that knows the namespace can read/write the data.
Reuses the same database table as pluginStore.
Store a value for the current user. Objects/arrays are auto-JSON-stringified.
| Param | Type | Description |
|---|---|---|
namespace |
string |
Access key (e.g. your space ID). Max 64 chars. |
key |
string |
Data key (e.g. "inventory"). Max 64 chars. |
value |
any |
Any JSON-serialisable value. Max 1024 chars after stringification. |
Returns: Promise<boolean>
const NS = "45637586_1234"; // your space ID = your namespace
await ArrivalSpace.userData.set(NS, 'inventory', { items: ['sword', 'shield'], gold: 100 });
await ArrivalSpace.userData.set(NS, 'prefs', { theme: 'dark' });Read a value. Auto-parses JSON by default.
| Param | Type | Description |
|---|---|---|
namespace |
string |
Access key |
key |
string |
Data key |
options.userId |
string? |
Read another user's data |
options.raw |
boolean? |
Return raw string instead of parsing JSON |
Returns: Promise<any | null | false> — parsed value, null if not found, false on error.
const inv = await ArrivalSpace.userData.get(NS, 'inventory');
console.log(inv.items); // ['sword', 'shield']
// Read another user's data
const other = await ArrivalSpace.userData.get(NS, 'inventory', { userId: '12345678' });Delete a key for the current user.
Returns: Promise<boolean>
List keys for the current user (or another user).
| Param | Type | Description |
|---|---|---|
namespace |
string |
Access key |
options.prefix |
string? |
Filter keys starting with this prefix |
options.userId |
string? |
List another user's keys |
options.limit |
number? |
Max keys (default 100) |
Returns: Promise<string[] | false>
const keys = await ArrivalSpace.userData.keys(NS);
// → ['inventory', 'prefs']
const invKeys = await ArrivalSpace.userData.keys(NS, { prefix: 'inv/' });A general one-shot LLM completion so any plugin can use AI — build an NPC,
a text tool, a classifier, anything. Backed by the platform's /ai/complete
endpoint. The plugin supplies its own system prompt and messages; the
entity/room only decides whose key and whose budget applies, never the
prompt.
The free platform model (GPT-6 Luna) is used by default, so a plugin works with
zero setup — no API key exists or is needed for it; don't ask the creator for
one. A space owner can optionally store their own OpenAI/Anthropic/GLM API key
server-side
(never visible to plugins or visitors) under Settings → Profile → AI Keys. That
paid key is spent only through a placed vibe entity the owner owns (pass
entityId), and defaults to a cheap model unless the owner set a model in
that entity's params.
Run a completion. Provide either prompt (one user turn, no history) or
messages (a chat, including prior turns for continuation).
| Param | Type | Description |
|---|---|---|
opts.system |
string? |
System prompt / instructions |
opts.prompt |
string? |
A single user message (sugar for messages:[{role:'user',content}]) |
opts.messages |
Array? |
Turns [{role: 'user'|'assistant', content, images?}] |
opts.images |
string[]? |
Images for the model to look at, with prompt (or added to the last user turn): https URLs or data: URLs (e.g. a canvas the plugin drew, a photo the visitor picked). At most 4 per request. Every provider takes them except an owner GLM key on a text-only model |
opts.provider |
string? |
'luna' (free, default) | 'openai' | 'anthropic' | 'glm' (owner key) |
opts.effort |
string? |
Free model only: 'low' | 'medium' (default) | 'high' — more reasoning: better code, slower, costs more of the daily budget |
opts.entityId |
string? |
The placed vibe entity ID — required to spend the owner's paid key |
opts.signal |
AbortSignal? |
Cancels: stops waiting and stops the model call server-side, freeing one of the visitor's 2 concurrent-call slots; resolves to { error: 'Cancelled.', code: 'aborted' } |
Returns: Promise<{answer, provider, model, effort, truncated, costUsd, inputTokens, outputTokens} | {error, code, scope?, resetsAt?} | null> —
null on network failure. truncated: true means the answer hit the 32k output-token limit and was cut off.
error is written to be shown to the visitor as-is (e.g. "You've used today's free AI allowance — it resets in 5h 12m.").
code |
Meaning |
|---|---|
budget_exceeded |
A daily budget is spent; scope is 'visitor', 'guest', 'space' or 'platform' (or 'owner' on an owner key); resetsAt is the ISO time it resets (UTC midnight) |
busy |
This visitor already has 2 free-model calls running (a space: 10) |
bad_request |
Input over the limits below, missing prompt, or an unknown space |
no_answer |
The model used its whole output budget reasoning and produced no text |
provider_error / not_configured |
Model unavailable |
aborted |
The call was cancelled through opts.signal |
The promise never rejects — a cancel included.
Limits. The free model takes coding-sized input: system ≤ 100,000 chars,
≤ 100 messages of ≤ 200,000 chars each, ≤ 400,000 chars in total; over that is a
bad_request, never silent truncation. It is free to the plugin and bounded by
daily dollar budgets — $0.50 per signed-in visitor, $0.10 per guest, $5 per
space — enough for hundreds of chat answers or ~15 very large coding requests a
visitor. Owner keys keep short NPC limits: system ≤ 4000 chars, the last 20
messages of ≤ 2000 chars each, 800-token answers. Long answers are fine: the
free model writes ~90 output tokens/s, so a large piece of code takes minutes,
and the promise resolves when it is done (the server hands over after 20 s and
ai.complete polls for the result).
On plugin instances there is a forwarder this.aiComplete(opts) that auto-fills
entityId with this entity's id.
// one-shot general question (no entity needed → free Luna)
const res = await ArrivalSpace.ai.complete({ prompt: 'Give me a fun fact about cats.' });
// NPC-style chat with continuation, on this entity
const res = await this.aiComplete({
system: this.prePrompt,
messages: [...this._history, { role: 'user', content: question }],
});
if (res?.answer) this._showAnswer(res.answer);
// let the model look at an image (an https URL, or a data: URL from a canvas you drew)
const seen = await this.aiComplete({ prompt: 'Describe this poster in one sentence.', images: [posterUrl] });
// long coding request that the visitor can cancel (or that dies with the plugin)
this._ai = new AbortController();
const code = await this.aiComplete({ effort: 'high', prompt: spec, signal: this._ai.signal });
if (code?.code === 'aborted') return;
// … in destroy() / a Cancel button: this._ai?.abort();Key status. Providers are 'openai' | 'anthropic' | 'glm'. Keys are a
profile/account setting that only the user sets, under
Settings → Profile → AI Keys; openKeySettings() navigates there (use it when
a paid provider is selected but keyStatus() shows no key). keyStatus()
returns {openai, anthropic, glm} booleans — keys themselves are never
returned by any endpoint. Owner keys are bounded by daily call caps per visitor,
entity, room and key-owner; the free platform model by the dollar budgets above.
Talk with an AI voice in realtime: the visitor speaks into the microphone and it answers aloud -
about half a second after they stop, and they can interrupt it (OpenAI gpt-realtime-2.1-mini,
browser to provider over WebRTC). The browser asks for the microphone on the first call. The
conversation is the local visitor's alone - other players don't hear it - and ends after 10
minutes, on stop(), or when entity is destroyed. Connecting takes about 4-5 s. Every
conversation - the instructions and what both sides said - is kept for review by the arrival.space
team. Requires ArrivalSpace.VERSION >= 1.24.0.
Voice conversations are a Business feature, paid by the space's owner: Business includes 300 voice
minutes a month, Business Plus 450. A conversation counts from its start to its last line (1-10
minutes); with quality: "high" every minute counts three times. Visitors need an account (a guest
gets the sign-up prompt) and have up to 20 conversations a day. In a space without a Business plan,
or with its minutes used up, it ends right away with error saying so.
It plays like a call, not positionally: the browser's echo cancellation only covers audio it plays itself, and a positional voice would hear itself through the speakers and interrupt itself.
| Option | Type | Default | Description |
|---|---|---|---|
instructions |
string |
a short friendly persona | Who it is and how it talks (up to 16000 characters) |
voice |
string |
'marin' |
alloy, ash, ballad, coral, echo, sage, shimmer, verse, marin, cedar |
quality |
`'standard' | 'high'` | 'standard' |
greeting |
string |
- | Said word for word first, before the visitor speaks |
tools |
Array<{ name, description, parameters?, run(args) }> |
- | Actions it can take while talking. It calls one when the conversation calls for it - the description says when; arguments follow parameters (JSON Schema). What run returns (or resolves to) goes back to it as the result, so it can talk about what happened - unless it is an object with silent: true: then the result goes back and no answer is asked for (1.33.0) |
pushToTalk |
boolean |
false |
Push to talk (1.33.0): the microphone open only between talk(true) and talk(false), and the visitor's turn ends at talk(false) - not at a pause - so it never answers into the middle of what they say. A radio's key, a walkie-talkie's button |
entity |
pc.Entity |
- | The conversation ends when this entity is destroyed; an avatar (an NPC's entity) moves its mouth with the voice |
volume |
number |
1 |
|
onUserText |
(text) => void |
- | What the visitor said (transcribed) or typed with sendText |
onReply |
(text) => void |
- | What it answered |
onStateChange |
(state) => void |
- | 'connecting', 'listening', 'speaking', 'ended' |
Returns: { done, stop(), say(text), sendText(text), setMicMuted(muted), talk(down), hasMicrophone, state, level, error }
done:Promise<void>, resolves when the conversation ends. Never rejects.say(text): the plugin's own words in the conversation, e.g. what the visitor clicked or an event ("[they walked out]").sendText(text): the visitor typing instead of speaking; counts as their words (onUserText, the transcript). 1.26.0.talk(down): push to talk, the key or button pressed (true) and let go (false); withpushToTalkthe turn ends when it is let go (a moment later: the last syllable is still on its way), without it the microphone is just opened and shut. 1.33.0.hasMicrophone:falsewhen there is no microphone or access was refused - it connects all the same and answers typed text aloud;nulluntil known. 1.26.0.level: its voice's loudness0..1while speaking, e.g. for a mouth.error: why it ended early (nullotherwise), in words for the visitor: sign up to talk, the space's plan or its voice minutes, the visitor's conversations today, connection lost. Before 1.26.0 also: no microphone.
OpenAI's usage policy requires telling visitors that the voice is AI-generated.
const chat = ArrivalSpace.ai.voiceChat({
instructions: "You are Marco, who has run this noodle stand for thirty years. Answer briefly.",
voice: "cedar", greeting: "Hi, I'm Marco - an AI voice. Hungry?", entity: npc.entity,
onStateChange: (s) => npc.setHeadLabel(`Marco (${s})`),
});
// chat.stop() when the visitor walks away// a tool: the AI calls it the moment the visitor agrees
ArrivalSpace.ai.voiceChat({
instructions: "You sell lemonade. When they agree to buy, call serve.",
tools: [{
name: "serve",
description: "Call when the visitor agrees to buy a lemonade - never before.",
parameters: { type: "object", properties: { size: { type: "string", enum: ["small", "large"] } }, required: ["size"] },
run: ({ size }) => { this.pourLemonade(size); return `A ${size} lemonade is on the counter.`; },
}],
});// push to talk: a radio, Tab held while speaking (1.33.0)
const radio = ArrivalSpace.ai.voiceChat({ instructions: "You are the tower controller.", pushToTalk: true });
this.onKeyDown("Tab", () => radio.talk(true), { consume: true });
this.onKeyUp("Tab", () => radio.talk(false));Example: examples/voice-npc.mjs - click an NPC and talk to it.
See examples/ai-npc.mjs for an LLM-driven NPC, and
examples/ai-text-tool.mjs for a non-NPC text
tool — both built on ai.complete.
See docs/multiplayer.md for attribute() and ArrivalSpace.net.
Control WebXR sessions (VR and AR passthrough) from plugins.
Returns the current XR state.
const state = ArrivalSpace.xr.getState();
// → { supported: true, active: false, mode: null, passthrough: false,
// availableVR: true, availableAR: true }| Property | Type | Description |
|---|---|---|
supported |
boolean |
Whether WebXR is supported by the browser |
active |
boolean |
Whether an XR session is currently running |
mode |
"vr" | "ar" | null |
The active session mode, or null if inactive |
passthrough |
boolean |
true when in AR passthrough mode |
availableVR |
boolean |
Whether immersive-vr is available on this device |
availableAR |
boolean |
Whether immersive-ar is available on this device |
Read-only boolean — true when any XR session is running.
Check whether a mode is available before entering.
if (ArrivalSpace.xr.isAvailable("ar")) {
console.log("Passthrough AR is supported on this device");
}| Param | Type | Description |
|---|---|---|
mode |
"vr" | "ar" |
The mode to check for |
Returns boolean.
Enter an XR session. Returns a promise.
// Enter AR passthrough (Quest 3)
const result = await ArrivalSpace.xr.enter({ mode: "ar" });
// Enter VR
const result = await ArrivalSpace.xr.enter({ mode: "vr" });
// AR without automatic passthrough rendering (manual control)
const result = await ArrivalSpace.xr.enter({ mode: "ar", passthrough: false });| Option | Type | Default | Description |
|---|---|---|---|
mode |
string |
"vr" |
"vr" for immersive-vr, "ar" for immersive-ar passthrough |
passthrough |
boolean |
true |
When true (AR only): hides skybox and clears to transparent |
spaceType |
string |
mode-dependent | Override XR reference-space. Defaults: AR → "local-floor", VR → "local" |
Returns Promise<{ success: boolean, error?: string }>.
When passthrough is true (the default for AR), the plugin API automatically:
- Sets the camera clear colour to transparent
(0, 0, 0, 0) - Hides the skybox (scales to zero)
- Restores both on session end
End the current XR session.
await ArrivalSpace.xr.exit();Returns Promise<{ success: boolean, error?: string }>.
Listen for XR session start and end events.
const unsub = ArrivalSpace.xr.onStateChange((state) => {
console.log("XR state changed:", state.active, state.mode);
});
// Later: stop listening
unsub();The callback receives the same state object as getState(). Returns an unsubscribe function.
createTexturePanel() and createHTMLPanel() internally apply 90 + rotation.x on the entity X axis. If you later set Euler angles directly, apply the same offset.
// Correct
panel.setEulerAngles(90 + rotation.x, rotation.y, rotation.z);The value returned by createTexturePanel() is the entity itself (not { entity }).
const panel = await ArrivalSpace.createTexturePanel(...);
panel.setPosition(x, y, z);Some static gates are flipped (about 180 on X). Detect and compensate when applying gate-relative rotations.
const gateRoot = gate.entity.findByName("root");
const rot = gateRoot.getEulerAngles();
const isFlipped = Math.abs(Math.abs(rot.x) - 180) < 1;Avoid recreating expensive objects unless required:
async onPropertyChanged(name) {
switch (name) {
case "offset":
case "rotationY":
this._updateTransforms();
break;
case "width":
case "height":
await this._recreate();
break;
default:
this._updateContent();
break;
}
}Gate links may be short IDs or full room names:
return link.startsWith("custom.travel.center.")
? link
: `custom.travel.center.${link}`;Space IDs are:
custom.travel.center.{creatorID} or custom.travel.center.{creatorID}_{num}
Call async setup from initialize() without awaiting:
initialize() {
this._setup();
}You have full access to the PlayCanvas engine API:
https://developer.playcanvas.com/api/
const box = new pc.Entity("Box");
box.addComponent("render", { type: "box" });
this.entity.addChild(box); // always parent to this.entity for auto-cleanupThe engine is PlayCanvas v2. The v1 API is gone: no model component (use render), no
pc.createMesh, no pc.createScript; build meshes with new pc.Mesh(device) and
new pc.MeshInstance(mesh, material).
- Mutating the Vec3 that
rigidbody.linearVelocityreturns does not move the body: assign it (rb.linearVelocity = v, dynamic bodies only) or useapplyImpulse/teleport. - On a child of a compound collider, add the rigidbody before the collision component - otherwise its shape also stays in the parent's compound.
- Collision shapes ignore entity scale, their own and their parents': size them in world units
(
halfExtents,radius,height). - The plugin's entity takes its entity's position and rotation, never its
data.scale: size what the vibe creates itself (e.g.this.createModel(url, { scale })).
Note: Always add sub-entities as children of this.entity, not this.app.root. Children of your plugin entity are auto-destroyed on unload. setPosition() and setRotation() set world-space transforms regardless of parent hierarchy, so parenting does not limit positioning.