Skip to content

Basic principles

Updated

Scripts give a world its logic. A Behavior script is a short JavaScript file attached to an entity: it runs while the world plays, reacts to time, to input and to other scripts, and changes the entities around it. Scripts are run by MIRA (Modular Immersive Reality Application), the runtime that turns a saved project into an interactive 3D world, in a desktop or mobile browser and in VR and AR headsets. The same runtime powers the editor, where worlds are authored, and the player, where people visit them.

The Scripting API is everything a script can reach: the scene it lives in, the entities of that scene and their components, with their props, methods and events, and the script globals such as Input, Tween and Network. This section sets out the principles behind them, each with a pointer to the section that covers it in depth, then the scripting language itself: how a script runs, the hooks it declares, the directives it is written with, the fields it shows in the editor, every global it can use, and how scripts talk to each other. Each section starts with the concepts, then walks through complete, runnable examples.

New to scripting? Start with Write your first script and the Key concepts in Getting started, then come back here.

Every topic links a live example you can run in this browser. Here is the smallest one:

A world is what a visitor enters. It is built from a project: one or more scenes, the assets they use (models, textures, sounds, videos) and the scripts that give them logic. The same world runs everywhere MIRA runs, without a separate build for each:

Where How people experience it
Desktop browser Mouse and keyboard, on screen.
Phone or tablet Touch, and the device’s sensors such as its accelerometer and camera.
VR headset Immersive, with controllers or hands.
AR headset or phone The world mixed with the real room: passthrough, anchors and room geometry.

A script can adapt to the device it runs on, for example with lighter effects on a phone. See Directives and the Input section.

A scene is one space of the world, and one scene can replace another or be added on top of it: see Scenes in Getting started. To a script, a scene is a saved hierarchy of entities under a scene root, an entity that also carries the scene-wide settings such as the sky, the fog and the environment lighting. In a script, scene is the scene the script is in, and the Scenes global loads and unloads scenes. See Scenes.

An entity is any object in a scene: a mesh, a light, a camera, a sound, a UI panel, a script. Each entity has a name, which scripts use to find it with findEntity('Door'), an id, a type, a transform relative to its parent, children, and components, which make it do things. Entities in Getting started describes each part.

An entity’s type decides what it is and which components it starts with. You choose the type when you add an entity in the editor, or when you construct its class from a script. The types are grouped in families:

FamilyEntities
SceneBehavior, Group, Scene Root
MeshesFloor, Kit Piece, Mesh Collada, Mesh Fbx, Mesh Gltf, Mesh Obj, Mesh Usdz, Primitive Mesh, Splat Mesh, Terrain, Water Mesh
EffectsDecal, Fire, Mask
MediaImage, Image GIF, Image Ktx2, Image SVG, Lottie, PDF, Text, Text 3d, Video
LightsAmbient Light, Directional Light, Hemisphere Light, Light Probe, Point Light, Rect Area Light, Spot Light
CamerasCamera Orthographic, Camera Perspective
AudioAudio, Audio Ambisonic, Audio Positional, Audio Tone, Audio Tone Positional, Audio Zone
NavigationNavmesh Link, Navmesh Surface, Spawn Point, Spot Point, Travel Point
InteractionSnap Zone
UIUI Avatar, UI Button, UI Checkbox, UI Divider, UI Drawing, UI Image, UI Input, UI Keyboard, UI Label, UI Layout, UI List, UI List Item, UI Menu, UI Menu Item, UI Notification, UI Panel, UI Progress, UI Render Scene, UI Render View, UI Slider, UI Spacer, UI Switch, UI Toggle Button, UI Video
Logic and AIAI Agent, AI Dialog, Persistable
XRXR Meshes, XR Planes, XR World

Each family is a section of this guide that lists its types, and each type has a page that shows:

  • What it is and when to use it, with worked examples.
  • Components: what a new entity of that type is made of, which components are required, and which you can add.
  • Props: every setting of its components, with its default value, its accepted range and its unit.
  • Events: what the entity reports to scripts through a Signal Emitter.
  • From a script: how to find the entity and change its settings.

The entities reference lists every type in one table, with its class name and the components it requires, starts with and supports.

What you do with an entity from a script, from reaching its components to moving it, switching it off or hiding it, is in Working with entities.

A component is one unit of behaviour and saved data on an entity. Instead of one huge object type that can do everything, an entity is assembled from the components it needs: a box that can be clicked is a mesh entity with a Geometry, a material and a Selectable.

Components in Getting started shows which component adds what.

Every component has props, the settings you edit in the editor and change from a script with setProps. Some components are required by their entity type and always present; the rest can be added and removed. See Components and the component catalog.

A Behavior script is JavaScript attached to an entity. What a Behavior is, where it lives, how it runs and the sandbox it runs in are explained for beginners in Behaviors in Getting started. To a script, it is made of these parts, each with its own page in this section:

  • Behavior. The component that holds a script (comp-behavior): its source code, its run order and the values of its editor fields. In the editor you add one as a Behavior entity, usually placed under the object it drives.
  • self. The entity the script’s Behavior is on. Scripts always use self, never this.
  • Hooks. Functions the engine calls: startup once when the script starts, update(dt, time) every frame, enable and disable when the script is switched on and off, dispose when it stops. A script lists its hooks with #pragma lifecycle(...). See Lifecycle hooks.
  • Directives. Lines that start with #, applied before the script runs. #pragma directives declare the hooks, the editor fields and what the script shares; bare directives such as #define and #if decide which lines are compiled. See Directives.
  • Slots. Editor fields a script declares with #pragma slot. Each slot is a field in the editor and a variable in the script that holds its value. See Slots.
  • Globals. The names the runtime gives every script: scene, findEntity, Input, Tween, Scenes, log, every component and entity class, THREE and the JavaScript standard library. See Globals.
  • The sandbox. A script sees only its globals. Browser names such as window, fetch and setTimeout are undefined, and the runtime provides its own tools instead.

Objects in a world often need to react to each other: a button opens a door, a coin adds to a score. MIRA connects them with signals: named messages, such as 'door/open', that anyone can raise and anyone can listen to.

  • A script raises a signal with emit('door/open') and listens with on('door/open', callback).
  • A component reports what happens to it (a click, a collision, a value change) as events. A Signal Emitter component on the same entity puts those events on a signal.
  • An Enable on Signal component switches an entity on or off when a signal arrives, without any code.

See Events and signals.

Editor Play
Purpose Authoring the world Running it
Behavior scripts Do not run, except editor tools Run through their hooks
Physics Not stepped Stepped
Clicking and grabbing objects Selects them for editing Interacts with them
Scene switching from scripts Not allowed Allowed

The two modes never mix, so a visitor’s player carries no editor code. A script can still carry editor code, such as a button that arranges objects, which runs only in the editor. See Editor and play and Editor scripts.

A world is data until it is played. When a scene loads, MIRA builds its entities, attaches their components and starts their scripts:

  1. The scene loads. Its entities are created with the components saved on them. Models, textures and sounds load in the background.
  2. Components do their work. A Geometry and a material draw a mesh, a light lights the scene, a Selectable makes an entity clickable. Most of a world needs no code at all.
  3. Scripts start. Each Behavior’s script has its directives preprocessed and is checked against the language rules, its top-level code runs once, and on the next frame its startup hook runs.
  4. Every frame, the engine updates the components, then calls each script’s update hook with the time since the last frame. Scripts move things, read input and react to events.
  5. Events flow between them. When something happens (a click, a collision, a sound ending) a component sends an event. A Signal Emitter puts those events on a named signal, and scripts listen to signals with on.
  6. The scene ends. When a scene unloads or an entity is destroyed, each script’s dispose hook runs and everything the script started (listeners, timers, tweens and requests) is released for it.

An error thrown by a hook or a listener stops the script, and the error goes to the script log. Behaviors run in play only; in the editor, only editor code runs. Behavior scripts walks through each step.

This walkthrough writes a script that makes an object bob up and down, with a height you set in the editor. A longer, beginner-paced tutorial is Write your first script.

  1. Add a Behavior entity and place it under the object to animate, such as a sphere.

  2. Replace the Behavior’s code with this script:

    Bobber.jx
    #pragma slot(ref=height, type=Slider, min=0, max=2, step=0.05, default=0.3, group="Bob")
    #pragma slot(ref=period, type=Number, min=0.2, max=10, default=2, group="Bob")
    #pragma lifecycle(startup, update)
    let target = null;
    let baseY = 0;
    function startup() {
    target = self.parent;
    baseY = target.position.y;
    log('Bobbing', target.name, 'by', height, 'm');
    }
    function update(dt, time) {
    const phase = (time / period) * M_TAU;
    target.position.y = baseY + Math.sin(phase) * height;
    }
  3. Select the Behavior: a Bob section shows a Height slider and a Period field. Adjust them.

  4. Press Play. The object moves up and down around its starting height, once every period seconds.

  • The two #pragma slot lines declare height and period: editor fields, and variables the script reads.
  • #pragma lifecycle(startup, update) names the hooks. startup keeps the target and its starting height; update sets the height every frame.
  • time is the seconds the world has been playing, so the motion depends only on time, not on the frame rate. M_TAU is a full turn, 2π.

New to scripting? Write your first script builds one step by step.

If you want… Use Read
To run code once, or every frame startup, update Lifecycle hooks
To run code later, or less often delay, debounce, throttle Time and tweens
To animate a value smoothly Tween, Ease Time and tweens
To react to a click, a collision or a UI control A Signal Emitter and on Events and signals
To switch things on and off when a signal arrives, without code Enable on Signal Events and signals
To send a message to other scripts emit with on or once Events and signals
To share a value or an API between scripts #pragma export and #pragma import Modules
One shared object, whoever asks first Singleton Modules
A JavaScript library from a CDN #pragma import(Name="url") Dynamic imports
A field to tune a script in the editor #pragma slot Slots
A tool or button that helps you author #editor_begin, #editor_only Editor scripts
Code for one kind of device only #if IS_MOBILE, #if IS_HEADSET Directives
To find, create or remove entities findEntity, spawn, destroy Scene and entities
To change, move, switch off or hide an entity getComponent, setPosition, setEnabled, visible Working with entities
To load data from a server HttpRequest Data and utilities
To move between levels Scenes Scenes
To see complete, working worlds Live examples Examples
To show a message or a dialog NotificationService Notifications

The globals most scripts use. The Globals page groups every one of them, and the globals reference lists them all.

GlobalWhat it is
selfThe entity the Behavior is on: self.position, self.getComponent(...). Its own Behavior is self.getComponent(BehaviorComponent).
sceneThe current scene fragment; live, so it always reflects the loaded scene. To delete an entity use scene.destroy(entity): it stops its scripts and frees its memory. scene.remove(entity) (and scene.clear()) stop the scripts but keep the memory, for an entity you will add back later.
findEntityFind an entity in the current scene by id, a map read fine every frame, or else by name among its entities.
spawnCopy an entity already in the scene (by name, or the entity itself) and add the copy with options.
destroySame as scene.destroy: remove an entity (or id) and its subtree, disposing them and stopping their scripts.
emitRaise a signal, with optional data, for every script and the app.
onCall callback(data) right away each time signal is emitted; returns a function that stops it. Released with the script.
onceCall callback(data) the next time signal is emitted, then stop; returns a function that stops it sooner. Released with the script.
offStop every listener this script added with on or once for signal; other scripts keep theirs.
EventTypeEvery event type a script can hear, by who sends it: compare them rather than typing the strings.
InputEvery input device: keyboard, mouse, touch, XR, accelerometer, gyroscope, microphone, device camera, location.
TimeMeasure with Time.now(), Time.since(start); game time: Time.scale, pause(), resume(), isPaused().
TweenAnimate any object's numbers: Tween.to(mesh.position, { x: 5 }, { duration: 1 }), from, value, stop; awaitable.
EaseThe easings, for { ease: Ease.OutCubic }: Linear, and In, Out and InOut of each curve (Quad, Cubic, Quart, Sine, Expo, Back, Elastic, Bounce). In starts slow, Out ends slow, InOut does both; Back overshoots a little, Elastic springs, Bounce bounces. Any function of progress 0..1 works as well.
SingletonNamed shared instances for this app: Singleton.get(key, factory), then Singleton.key.
logWrite values to the script log.
ComponentTypeWhat it does
Behaviorcomp-behaviorHolds a user script and its run order.
Enable On Signalcomp-enable-on-signalEnables, disables or toggles the entity when a signal arrives.
Signal Emittercomp-signal-emitterCollects events from sibling components and sends them on as signals.
Topic Description
Behavior scripts What a Behavior is, how a script runs, the sandbox and the language rules.
Lifecycle hooks Every hook, its signature, the run order, enabling and disabling, async hooks.
Scene and entities self, scene, finding, spawning and destroying entities, the camera and the project’s variables.
Working with entities What an entity is, its members, components, transform setters, Enable and visible, and the hierarchy.
Events and signals The event bus, emit, on, once and off, EventType, Signal Emitter and Enable on Signal.
Time and tweens delay, debounce, throttle, Time and game time, Tween and Ease.
Slots Editor fields: every slot type and option, enums, records and lists.
Globals Every name a script can use, grouped by purpose.
Directives #define, #if, predefined constants and macros, device flags and every #pragma.
Data and utilities HTTP requests, canvases, random numbers, object pools, streams, fonts, THREE and logging.
Modules Exports and imports between scripts, and Singleton.
Dynamic imports Libraries from a CDN with #pragma import(Name="url"): pinning, ES modules and UMD, several names, and worked examples.