Time and tweens
Updated
Interactive worlds are full of timing: a door that closes after three seconds, a coin that bobs up and down, a slow-motion power-up, a save that waits until the player stops dragging a slider. Scripts have no setTimeout or setInterval. Instead they get delay, debounce and throttle to run code later or less often, Time to measure durations and to slow down, speed up or pause the game, and Tween with Ease to animate any object’s numbers smoothly. Everything a script schedules is tied to it: when the script stops, its timers and tweens stop too.
| Global | What it is |
|---|---|
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. |
Time | Measure with Time.now(), Time.since(start); game time: Time.scale, pause(), resume(), isPaused(). |
delay | |
debounce | |
throttle |
Before you start
Section titled “Before you start”- The
update(delta, time)hook runs every frame;deltais the seconds since the last frame. See Lifecycle hooks. awaitworks only inside anasyncfunction, such asasync function startup().- For authored keyframe motion, or the clips inside a model, use an Animation Timeline or an Animation Clip instead of tweens.
- Moving an entity by writing
entity.positiondiffers from callingentity.setPosition. See Working with entities.
Game time and real time
Section titled “Game time and real time”MIRA keeps two clocks:
- Game time is what every frame moves the scene by: physics, animations, components, tweens,
delay,debounce, and thedeltayourupdatereceives.Time.scalespeeds it up or slows it down, andTime.pause()stops it. - Real time goes on regardless:
Time.now(), input, the pointer and the UI, rendering, a headset’s tracking, video, audio and the network.
Rules of game time:
- Scripts keep running while paused.
updateis still called, with adeltaof 0, so a script can read a key and callTime.resume(). Code that moves things bydeltastands still on its own. - For this player only. In a multiplayer scene, other players are not paused or slowed.
- One per app. Every script sees the same
Time.scaleand pause state. A play session starts at scale1, not paused; a scene switch keeps both. - Physics keeps up to a point. At very high scales, physics falls behind rather than taking ever more steps per frame. A scale of up to about 4 is safe at 60 frames a second.
| Member | What it does |
|---|---|
Time.now() |
Milliseconds since the page loaded, with fractions. Never goes backwards, ignores changes to the computer’s clock. |
Time. |
Milliseconds since start, a value from Time.now(). |
Time.scale |
How fast game time runs: 1 normal, 0.5 half speed, 2 double. Any number 0 or more; anything else throws a RangeError. |
Time.pause() |
Stops game time. Time.scale is kept. |
Time.resume() |
Carries on after pause(), at Time.scale. |
Time. |
Whether game time is stopped. |
Use Time.now() to measure durations and Date.now() for the calendar date. To time a frame, use the delta your update hook already receives, in seconds.
delay, debounce and throttle
Section titled “delay, debounce and throttle”| Global | What it does | Returns |
|---|---|---|
delay(fn, ms = 0, ... |
Runs fn(...args) once, ms milliseconds of game time from now. 0 runs it on the next frame. |
A function that cancels the call if it has not run yet; safe to call twice. |
debounce(fn, ms) |
Makes a version of fn that waits for calls to stop: each call restarts the wait, and fn runs once, ms after the last call, with that call’s arguments. |
The debounced function, with cancel() to drop a pending run. |
throttle(fn, ms) |
Makes a version of fn that runs at most once every ms. The first call runs at once; calls sooner than ms after the last run are dropped, not queued. |
The throttled function, which returns true when it ran and false when the call was dropped. |
- Game time. A delay counts the engine’s frames, so it pauses while the game is paused or the browser tab is hidden. It runs on the frame it falls due, before that frame’s
update. - Cleanup. Pending delays and debounced runs are cancelled when the script stops, so a destroyed object never runs them.
- Errors. An error thrown, or a promise rejected, in
fngoes to the script log. - Waiting in an async hook.
delayneeds a function. To pause inside anasyncfunction, wrap it:await new Promise((done) => delay(done, 500)).
When to use which: delay for “do this later”, debounce for “do this once the user stops” (saving, searching), throttle for “do this at most this often” (firing, network updates).
A tween (from “in-between”) animates an object’s numeric properties from their current values to new ones over a set time: a position, a rotation, a scale, a colour’s r, g and b, a material’s opacity, a light’s intensity. A door turns 90 degrees in 0.8 seconds, a pickup bobs up and down, a button grows when clicked. You give the target values and a duration; the tween computes every frame in between. Tweens need no authoring and no components, so they are the quickest way to animate from a script.
| Call | What it does |
|---|---|
Tween. |
Animates target’s numbers from what they are when it starts to values. |
Tween. |
Animates from values back to what they are now. |
Tween. |
Animates a plain number, handing each value to on. |
Tween. |
Stops every tween moving target. |
Options
Section titled “Options”| Option | Default | What it sets |
|---|---|---|
duration |
1 |
Seconds it takes. 0 jumps to the end on the next frame. |
ease |
Ease.OutQuad |
How it speeds up and slows down: one of Ease, or any function of progress from 0 to 1. |
delay |
0 |
Seconds to wait before starting. |
repeat |
0 |
Times to play again after the first; Infinity for ever. |
yoyo |
false |
Plays every other repeat backwards. |
on |
none | Called every frame it moves, with the progress of the current play, 0 to 1. |
onComplete() |
none | Called once when it finishes; not when it is stopped. |
The tween handle
Section titled “The tween handle”Each call returns a handle you can control and await:
| Member | What it is |
|---|---|
stop() |
Stops where it is. |
pause(), resume() |
Holds it where it is; carries on. |
isPlaying |
true until it finishes or is stopped, paused or not. |
progress |
The progress of the current play, 0 to 1. A property, not a method. |
await tween |
Resolves true when it finished, false when it was stopped. |
Tween rules
Section titled “Tween rules”- Frame timing. Tweens advance before the scripts’
update, soupdatesees this frame’s values, and tweens pause with the game. - Start values are read when a tween starts, after its
delay, so a chain ofawaits follows on from each step. - Newer wins. A new tween on a property another tween is moving takes that property over.
- Numbers only. Each value must be a finite number, and the target must already have a number under that key, or the call throws. Animate
rotation(Euler angles), not a quaternion’s components. - Lifetime. A script’s tweens stop when it stops; an
awaiton one then never resumes. - Entities. Tweening
entity.positionwrites it directly: it moves what is drawn but sends no Transform events and does not move a physics body. When those matter, tween a value withTween.valueand callsetPositionin its callback, or inonUpdate.
An easing curve maps the tween’s linear progress (0 to 1) to a shaped progress, so motion can start gently, stop gently, overshoot or bounce. Ease holds the easing curves: Linear, and the In, Out and InOut forms of Quad, Cubic, Quart, Sine, Expo, Back, Elastic and Bounce (Ease.InQuad, Ease.OutBack, Ease.InOutBounce…).
| Family | Feel |
|---|---|
In… |
Starts slow, ends fast. Good for things leaving. |
Out… |
Starts fast, ends slow. The most natural for things arriving and coming to rest; OutQuad is the default. |
InOut… |
Slow at both ends. Good for back-and-forth motion, and for doors, cameras, anything that starts and stops at rest. |
Quad, Cubic, Quart, Expo |
Increasingly strong acceleration. |
Sine |
The gentlest curve; ideal for bobbing and breathing. |
…Back |
Overshoots a little, then settles. Lively for pop-ins. |
…Elastic |
Springs past the end and wobbles. |
…Bounce |
Bounces at the end like a dropped ball. |
Any function of progress works too: const steps = (t) => Math.floor(t * 4) / 4; moves in four jumps.
Try it
Section titled “Try it”A ball that bobs for ever, a box that turns and waits, and a shape that pulses when clicked, all from one script:
Three tweens from one script: a ball that bobs for ever, a box that turns and waits, and a shape that pulses when you click it, awaiting each step.
Click the diamond on the right to make it pulse. Drag to orbit the camera, scroll to zoom.
#pragma lifecycle(startup)
async function startup() { const bob = findEntity('Bob'); const turn = findEntity('Turn'); const pulse = findEntity('Pulse');
// Up and down for ever: repeat with yoyo plays every other run backwards. Tween.to(bob.position, { y: 1.8 }, { duration: 1.2, ease: Ease.InOutSine, repeat: Infinity, yoyo: true });
// Click: grow, then shrink back, one awaited step after the other. on('pulse/clicked', async (event) => { if (event.eventType !== EventType.Selectable.Select) return; // Select fires only on becoming selected: release it so every click counts. pulse.getComponent(SelectableComponent).setSelected(false); await Tween.to(pulse.scale, { x: 1.5, y: 1.5, z: 1.5 }, { duration: 0.25, ease: Ease.OutBack }); await Tween.to(pulse.scale, { x: 1, y: 1, z: 1 }, { duration: 0.4 }); log('Pulsed'); });
// A quarter turn, a pause, and again. for (;;) { await Tween.to(turn.rotation, { y: turn.rotation.y + Math.PI / 2 }, { duration: 0.8, ease: Ease.InOutCubic }); if (!(await Tween.value(0, 1, () => {}, { duration: 0.6 }))) return; }}startupisasync, so it canawaittweens. The engine does not wait for it; the endless loop at the end runs alongside everything else.- The bob tween never ends:
repeat: Infinitywithyoyo: truegoes up and down for ever, andEase.InOutSinemakes the turnarounds soft. - The click handler is itself
async: eachawaitwaits for one step, so the shape grows, then shrinks, then logs. - The loop turns the box by a quarter turn, reading
turn.rotation.yafresh each time.Tween.value(0, 1, () => {}, …)is used as a 0.6 second wait; it resolvesfalseif it was stopped (for example when the script is released), and the loop then ends.
Examples
Section titled “Examples”1. Bob up and down
Section titled “1. Bob up and down”A pickup that floats gently for ever.
#pragma slot(ref=height, type=Number, min=0, max=2, default=0.2)#pragma slot(ref=seconds, type=Number, min=0.1, max=10, default=1.2)#pragma lifecycle(startup)
function startup() { const target = self.parent; Tween.to(target.position, { y: target.position.y + height }, { duration: seconds, ease: Ease.InOutSine, repeat: Infinity, yoyo: true, });}A pickup that floats up and down for ever: one Tween with repeat: Infinity, yoyo and an InOutSine ease.
Watch the pickup float. Drag to orbit the camera, scroll to zoom.
How it works
Tween.toanimatesposition.yfrom where it is toheighthigher.repeat: Infinityplays it for ever, andyoyo: trueplays every other run backwards, so it goes up and down.Ease.InOutSineslows at both ends for a soft float.- The tween stops by itself when the script stops.
2. A pickup that bobs and pops
Section titled “2. A pickup that bobs and pops”A collectible bobs gently; when a pickup/taken signal arrives, it stops bobbing, shrinks away and removes itself.
#pragma lifecycle(startup)
async function startup() { const start = self.parent.position.y; Tween.to(self.parent.position, { y: start + 0.2 }, { ease: Ease.InOutSine, repeat: Infinity, yoyo: true }); Tween.to(self.parent.rotation, { y: M_TAU }, { duration: 3, ease: Ease.Linear, repeat: Infinity });
on('pickup/taken', async () => { Tween.stop(self.parent.position); Tween.stop(self.parent.rotation); await Tween.to(self.parent.scale, { x: 0, y: 0, z: 0 }, { duration: 0.3, ease: Ease.InBack }); destroy(self.parent); });}Two endless tweens bob and spin a pickup; on pickup/taken they stop, a third shrinks it away, and the pickup is destroyed.
Watch the gem bob and spin, then press Take to make it pop and vanish. Drag to orbit the camera, scroll to zoom.
- The bob rises 0.2 m over the default one second and comes back, for ever.
- The spin turns a full circle (
M_TAU, 2π radians) in 3 seconds withEase.Linear, so it never slows down. Withrepeat, each run starts again from where the tween first started, giving a continuous rotation. Tween.stoptakes the object being animated and stops every tween on it.Ease.InBackpulls back slightly before shrinking, a small anticipation that reads well.destroyruns only after the shrink finishes, because the handler awaits the tween.
3. A door that closes by itself
Section titled “3. A door that closes by itself”Open a door on a signal, wait, then close it, with each step awaited.
#pragma slot(ref=holdSeconds, type=Number, min=0, max=30, default=3)#pragma lifecycle(startup)
let door = null;let busy = false;
function wait(ms) { return new Promise((done) => delay(done, ms));}
async function cycle() { if (busy) return; busy = true; await Tween.to(door.rotation, { y: Math.PI / 2 }, { duration: 0.8, ease: Ease.InOutCubic }); await wait(holdSeconds * 1000); await Tween.to(door.rotation, { y: 0 }, { duration: 0.8, ease: Ease.InOutCubic }); busy = false;}
function startup() { door = findEntity('Door'); on('door/open', cycle);}How it works
waitwrapsdelayin a promise, so anasyncfunction can pause for a while.- Each
awaitwaits for one step to finish before starting the next. - The
busyflag ignores new requests while a cycle runs. - If the script stops mid-cycle, its tweens and delay are cancelled and the
awaitnever resumes, so no code runs against a removed door.
4. Slow motion and pause
Section titled “4. Slow motion and pause”A power-up that slows the game, and a key that pauses and resumes. Time controls game time for every script and component at once.
#pragma lifecycle(startup, update)
let cancelSlowMo;
function startup() { on('powerup/slow-motion', () => { cancelSlowMo?.(); Time.scale = 0.3; cancelSlowMo = delay(() => (Time.scale = 1), 1500); });}
function update() { if (!Input.keyboard.isKeyReleased(Key.Escape)) return; if (Time.isPaused()) { Time.resume(); log('Resumed'); } else { Time.pause(); log('Paused'); }}A power-up sets Time.scale to 0.3 for 1.5 seconds, slowing everything driven by game time, and Escape pauses and resumes the game.
Press Slow motion to slow the balls for a moment. Click the scene and press Escape to pause, and again to resume.
- Setting
Time.scaleto0.3slows physics, animations, tweens andupdate(dt)to 30 percent. delaycounts game time, so at a scale of 0.3 its 1500 milliseconds last 5 real seconds: a long, dramatic slow motion. Calling the previous cancel function first means a second power-up restarts the timer instead of ending the first one early.- Escape toggles the pause.
updatestill runs while paused (withdt0), which is why the script can resume. isKeyReleasedfires once per press, so one press toggles once.
5. Fire, search and measure
Section titled “5. Fire, search and measure”Throttle a weapon, debounce a slider, and time a heavy job, in one script.
#pragma lifecycle(startup, update)
const fire = throttle(() => { spawn('Bullet', { position: self.parent.position, enabled: true });}, 250);
const saveVolume = debounce((value) => { emit('settings/save', { volume: value }); log('Saved volume', value);}, 400);
function rebuildGrid() { const start = Time.now(); for (let i = 0; i < 100000; i++) Math.sqrt(i); log(`Grid rebuilt in ${Time.since(start).toFixed(2)} ms`);}
function startup() { on('volume', (event) => { if (event.eventType === EventType.UISlider.Change) saveVolume(event.data.value); }); rebuildGrid();}
function update() { if (Input.keyboard.isKeyPressed(Key.Space)) fire();}How it works
fireruns at most four times a second however long Space is held; extra calls are dropped.- While the player drags a slider,
saveVolumeis called many times, but it runs once, 400 ms after the last change. Time.now()andTime.since()measure real elapsed milliseconds, unaffected byTime.scale.- The
Bulletentity is a disabled template copied withspawn. See Scene and entities.
Snippets
Section titled “Snippets”1. A physics-friendly lift
Section titled “1. A physics-friendly lift”Tweening position directly does not move a physics body. For a platform with a kinematic body, tween a plain number and apply it with setPosition.
#pragma lifecycle(startup)
let travel;
async function startup() { const lift = self.parent; const x = lift.position.x; const z = lift.position.z; const bottom = lift.position.y;
on('lift/call', async (floorHeight) => { travel?.stop(); travel = Tween.value(lift.position.y, bottom + floorHeight, (y) => lift.setPosition(x, y, z), { duration: 2, ease: Ease.InOutQuad, }); if (await travel) emit('lift/arrived', floorHeight); });}Tween.valueanimates a number and hands each value to the callback, which callssetPosition. That keeps the physics body andTransformevents in step.- A new call stops the previous trip with
travel?.stop()and starts from the current height, so the lift can change direction smoothly. await travelresolvestrueonly when the trip completed, solift/arrivedis not sent for an interrupted trip.emit('lift/call', 4)from a button script sends the lift to 4 m above its start.
2. Measure how long something takes
Section titled “2. Measure how long something takes”Time.now() and Time.since() are a precise stopwatch in real time.
#pragma lifecycle(startup)
function startup() { let started;
on('race/start', () => { started = Time.now(); });
on('race/finish', () => { if (started === undefined) return; const seconds = Time.since(started) / 1000; log(`Finished in ${seconds.toFixed(2)} s`); started = undefined; });}Time.now()returns milliseconds with fractions and never goes backwards, even if the computer’s clock changes.Time.since(started)is the elapsed real time; divide by 1000 for seconds.- Because
Time.now()is real time, the stopwatch keeps counting during slow motion and pauses. For game time, add updtinupdateinstead.
Common mistakes
Section titled “Common mistakes”Passing a number to delay
Section titled “Passing a number to delay”async function startup() { await delay(500); // throws a TypeError: delay needs a function}async function startup() { await new Promise((done) => delay(done, 500));}await outside an async function
Section titled “await outside an async function”#pragma lifecycle(startup)
function startup() { await Tween.to(self.parent.scale, { x: 2, y: 2, z: 2 }); // does not compile}#pragma lifecycle(startup)
async function startup() { await Tween.to(self.parent.scale, { x: 2, y: 2, z: 2 });}Tweening a quaternion or a string
Section titled “Tweening a quaternion or a string”Tweens animate numbers only. Animate rotation (an Euler), not quaternion.
Tween.to(box.quaternion, { y: 0.7 }); // breaks the rotationTween.to(box.rotation, { y: Math.PI / 2 });Calling progress as a method
Section titled “Calling progress as a method”log(tween.progress()); // TypeError: progress is not a functionlog(tween.progress);Moving a physics body with a tween
Section titled “Moving a physics body with a tween”Tweening crate.position moves the drawing but leaves its body and colliders behind. Tween a plain value and place the entity with its setter:
const startY = crate.position.y;Tween.value(startY, startY + 2, (y) => crate.setPosition(crate.position.x, y, crate.position.z), { duration: 1 });Moving by a fixed amount per frame
Section titled “Moving by a fixed amount per frame”function update() { self.parent.rotation.y += 0.02; // faster on faster screens, ignores pause}function update(dt) { self.parent.rotation.y += 1.2 * dt; // 1.2 radians a second, stops when paused}Expecting onComplete after stop()
Section titled “Expecting onComplete after stop()”onComplete runs only when a tween finishes. Check the awaited result instead: false means stopped.
Starting a new tween every frame
Section titled “Starting a new tween every frame”Each call replaces the last on the same property and restarts the motion. Start tweens from events or startup, not from update.
Pausing and finding nothing responds
Section titled “Pausing and finding nothing responds”Time.pause() stops game time for every script; read input in update to resume.