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 box that spins every frame and takes a new colour when you click it: a Behavior script, a Selectable and a Signal Emitter.
Click the box. Drag to orbit the camera, scroll to zoom.
Where worlds run
Section titled “Where worlds run”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.
What a world is made of
Section titled “What a world is made of”Scenes
Section titled “Scenes”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.
Entities
Section titled “Entities”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.
Entity types
Section titled “Entity types”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:
| Family | Entities |
|---|---|
| Scene | Behavior, Group, Scene Root |
| Meshes | Floor, Kit Piece, Mesh Collada, Mesh Fbx, Mesh Gltf, Mesh Obj, Mesh Usdz, Primitive Mesh, Splat Mesh, Terrain, Water Mesh |
| Effects | Decal, Fire, Mask |
| Media | Image, Image GIF, Image Ktx2, Image SVG, Lottie, PDF, Text, Text 3d, Video |
| Lights | Ambient Light, Directional Light, Hemisphere Light, Light Probe, Point Light, Rect Area Light, Spot Light |
| Cameras | Camera Orthographic, Camera Perspective |
| Audio | Audio, Audio Ambisonic, Audio Positional, Audio Tone, Audio Tone Positional, Audio Zone |
| Navigation | Navmesh Link, Navmesh Surface, Spawn Point, Spot Point, Travel Point |
| Interaction | Snap Zone |
| UI | UI 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 AI | AI Agent, AI Dialog, Persistable |
| XR | XR 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.
Components
Section titled “Components”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.
Behavior scripts
Section titled “Behavior scripts”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 useself, neverthis.- Hooks. Functions the engine calls:
startuponce when the script starts,update(dt, time)every frame,enableanddisablewhen the script is switched on and off,disposewhen it stops. A script lists its hooks with#pragma lifecycle(...). See Lifecycle hooks. - Directives. Lines that start with
#, applied before the script runs.#pragmadirectives declare the hooks, the editor fields and what the script shares; bare directives such as#defineand#ifdecide 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,THREEand the JavaScript standard library. See Globals. - The sandbox. A script sees only its globals. Browser names such as
window,fetchandsetTimeoutareundefined, and the runtime provides its own tools instead.
Signals and events
Section titled “Signals and events”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 withon('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 and play
Section titled “Editor and play”| 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.
How a world runs
Section titled “How a world runs”A world is data until it is played. When a scene loads, MIRA builds its entities, attaches their components and starts their scripts:
- The scene loads. Its entities are created with the components saved on them. Models, textures and sounds load in the background.
- 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.
- 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
startuphook runs. - Every frame, the engine updates the components, then calls each script’s
updatehook with the time since the last frame. Scripts move things, read input and react to events. - 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. - The scene ends. When a scene unloads or an entity is destroyed, each script’s
disposehook 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.
Your first script
Section titled “Your first script”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.
-
Add a Behavior entity and place it under the object to animate, such as a sphere.
-
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;} -
Select the Behavior: a Bob section shows a Height slider and a Period field. Adjust them.
-
Press Play. The object moves up and down around its starting height, once every
periodseconds.
- The two
#pragma slotlines declareheightandperiod: editor fields, and variables the script reads. #pragma lifecycle(startup, update)names the hooks.startupkeeps the target and its starting height;updatesets the height every frame.timeis the seconds the world has been playing, so the motion depends only on time, not on the frame rate.M_TAUis a full turn, 2π.
Your first script: a Behavior under a sphere bobs it around its starting height, with the height and period as editor slots.
Watch the ball bob. Drag to orbit the camera, scroll to zoom.
Choosing
Section titled “Choosing”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_ |
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 | Notification |
Notifications |
In scripts
Section titled “In scripts”The globals most scripts use. The Globals page groups every one of them, and the globals reference lists them all.
| Global | What it is |
|---|---|
self | The entity the Behavior is on: self.position, self.getComponent(...). Its own Behavior is self.getComponent(BehaviorComponent). |
scene | The 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. |
findEntity | Find an entity in the current scene by id, a map read fine every frame, or else by name among its entities. |
spawn | Copy an entity already in the scene (by name, or the entity itself) and add the copy with options. |
destroy | Same as scene.destroy: remove an entity (or id) and its subtree, disposing them and stopping their scripts. |
emit | Raise a signal, with optional data, for every script and the app. |
on | Call callback(data) right away each time signal is emitted; returns a function that stops it. Released with the script. |
once | Call callback(data) the next time signal is emitted, then stop; returns a function that stops it sooner. Released with the script. |
off | Stop every listener this script added with on or once for signal; other scripts keep theirs. |
EventType | Every event type a script can hear, by who sends it: compare them rather than typing the strings. |
Input | Every input device: keyboard, mouse, touch, XR, accelerometer, gyroscope, microphone, device camera, location. |
Time | Measure with Time.now(), Time.since(start); game time: Time.scale, pause(), resume(), isPaused(). |
Tween | Animate any object's numbers: Tween.to(mesh.position, { x: 5 }, { duration: 1 }), from, value, stop; awaitable. |
Ease | The 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. |
Singleton | Named shared instances for this app: Singleton.get(key, factory), then Singleton.key. |
log | Write values to the script log. |
Components
Section titled “Components”| Component | Type | What it does |
|---|---|---|
| Behavior | comp-behavior | Holds a user script and its run order. |
| Enable On Signal | comp-enable-on-signal | Enables, disables or toggles the entity when a signal arrives. |
| Signal Emitter | comp-signal-emitter | Collects events from sibling components and sends them on as signals. |
In this section
Section titled “In this section”| 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. |