Scripting API
This is the complete list of what code scripts can use. It is the same list the code editor’s autocomplete and API help sheet show. For an introduction, read Code scripts.
Lifecycle functions
Define any of these in a script; the engine calls them.
| Function | When it runs | Object script | Game script |
|---|---|---|---|
start() | Called once when the scene starts. | ✔ | ✔ |
update(dt) | Called every frame. dt = seconds since last frame. | ✔ | ✔ |
lateUpdate(dt) | Called every frame after physics. | ✔ | |
onCollision(other) | This entity started touching other. | ✔ | |
onCollisionEnd(other) | This entity stopped touching other. | ✔ | |
onTap() | The player tapped this entity. | ✔ | |
onClick() | This UI button was clicked. | ✔ | |
onDestroy() | This entity is about to be destroyed. | ✔ |
entity — entity
The entity the script is attached to (also other in collisions, and results of game.find()).
| Member | Type | Description |
|---|---|---|
id | string | Unique id of this entity. |
name | string | Object type name (clones share it), e.g. "Coin". |
tags | Set | Tags of this entity (read-only set). Use hasTag/addTag. |
destroyed | boolean | True once the entity has been destroyed. |
position | {x,y,z} | Local position in meters. Writable: entity.position.y += 1 |
rotation | {x,y,z} | Local rotation in DEGREES. Writable: entity.rotation.y += 90 * dt |
scale | {x,y,z} | Local scale. Writable: entity.scale.x = 2 |
visible | boolean | Show / hide the entity. |
enabled | boolean | Disabled entities are not updated or drawn. |
getVar(name) | value | Read an instance variable. |
setVar(name, value) | void | Write an instance variable. |
hasTag(tag) | boolean | Does this entity have the tag? e.g. other.hasTag("enemy") |
addTag(tag) | void | Add a tag. |
removeTag(tag) | void | Remove a tag. |
getWorldPosition() | {x,y,z} | Position in world space (includes parents). |
getForward() | {x,y,z} | Unit vector the entity faces (world space). |
setPosition(x, y, z) | void | Teleport to a position. |
translate(x, y, z) | void | Move by an offset in world axes. |
moveLocal(x, y, z) | void | Move along its own axes (x right, y up, z forward). |
setRotation(x, y, z) | void | Set rotation in degrees. |
rotate(x, y, z) | void | Rotate by degrees, e.g. entity.rotate(0, 90 * dt, 0) |
lookAt(x, y, z) | void | Turn to face a world point. |
moveToward(x, y, z, distance) | void | Move up to distance meters toward a point. |
distanceTo(otherOrPoint) | number | Distance to another entity or {x,y,z}. |
hasBody() | boolean | Has a RigidBody component? |
getVelocity() | {x,y,z} | Physics velocity (m/s). |
setVelocity(x, y, z) | void | Set physics velocity. |
applyImpulse(x, y, z) | void | Instant push, e.g. a jump: applyImpulse(0, 5, 0) |
applyForce(x, y, z) | void | Continuous push (call every frame). |
isOnGround() | boolean | True if a dynamic body rests on something. |
setColor(hex) | void | Change material color, e.g. setColor("#ff0000") |
setOpacity(0..1) | void | Change material opacity. |
setText(text) | void | Set the text of a Text component. |
getText() | string | Get the text of a Text component. |
getUIValue() | number | Progress bar value (UI component). |
setUIValue(value) | void | Set the progress bar value, e.g. health. |
getUIMax() | number | Progress bar maximum. |
setUIMax(max) | void | Set the progress bar maximum. |
setUIImage(assetName) | void | Change the image of a UI element. |
setUIColors({ background, text, fill }) | void | Change UI colors, e.g. { background: "#ff0000" }. |
isPressed() | boolean | True while this UI button is held down. |
playAnimation(name: string, loop = true) | void | Play a clip of the 3D model, e.g. "walk" or "jump". loop=false plays once and holds the last frame. |
stopAnimation() | void | Stop the playing model animation. |
getAnimation() | string | Name of the playing clip (empty if none). |
getAnimationNames() | string[] | All clip names of the model. |
hasAnimation(name: string) | boolean | True if the model has this clip. |
setAnimationSpeed(speed: number) | void | 1 = normal, 0.5 = half, 2 = double. |
tween(property, to, seconds, ease?) | void | Animate 'x' | 'y' | 'z' | 'angle' | 'size' | 'opacity' to a value, e.g. tween('size', 1.5, 0.3, 'back'). Eases: linear, easeIn, easeOut, easeInOut, back, elastic, bounce. |
isTweening(property?) | boolean | A tween is running (of that property, or any). |
stopTweens() | void | Stop all tweens where they are. |
attachTo(parent) | void | Carry this object along with another (keeps its place in the world), e.g. a picked-up key. |
detach() | void | Let go: back to the top level where it is now. |
emitParticles(count: number) | void | Shoot particles at once from the Particles component, e.g. emitParticles(30) on a hit. |
startParticles() | void | Start (or restart) the Particles component; also fires its Burst. |
stopParticles() | void | Stop making new particles (the ones out fade normally). |
setParticleRate(rate: number) | void | Particles per second while emitting. |
isEmittingParticles() | boolean | True while the Particles component makes new particles. |
getParticleCount() | number | Particles currently alive. |
playSound() | void | Play this entity's Audio component. |
stopSound() | void | Stop this entity's Audio component. |
setBehaviorEnabled(type, on) | void | Enable/disable a behavior, e.g. ("platformer", false) |
getBehaviorParam(type, param) | value | Read a behavior parameter. |
setBehaviorParam(type, param, value) | void | Change a behavior parameter, e.g. ("platformer", "speed", 8) |
getParent() | entity|null | Parent entity. |
getChildren() | entity[] | Child entities. |
destroy() | void | Remove the entity (at end of frame). |
object3d | THREE.Object3D | Advanced: the underlying three.js object. |
game — game
The running game.
| Member | Type | Description |
|---|---|---|
project | ProjectData | The whole project data (read-only). |
scene | SceneData | Current scene data (read-only). |
time | number | Seconds since the scene started. |
dt | number | Last frame time in seconds. |
timeScale | number | Game speed: 1 normal, 0.5 slow motion. |
paused | boolean | Is the game paused? |
input | input | Same as input. |
audio | audio | Same as audio. |
screen | {width,height} | Screen size in pixels. |
select(selector) | entity[] | All entities by name or #tag: game.select("#enemy") |
find(nameOrId) | entity|null | First entity with that name/id: game.find("Player") |
getAllEntities() | entity[] | Every live entity. |
spawn(name, position?, rotation?) | entity|null | Create a prefab / clone: game.spawn("Coin", {x:0,y:5,z:0}) |
destroy(entity) | void | Destroy an entity. |
pick(screenX, screenY) | entity|null | Entity at a screen point. |
hasLineOfSight(a, b) | boolean | True when nothing solid is between the two objects, e.g. an enemy can see the player. |
raycast(from, to) | {entity,point,distance}|null | Physics ray between two world points. |
isTouching(a, b) | boolean | Are two entities touching? |
getVar(name) | value | Read a global/scene variable: game.getVar("Score") |
setVar(name, value) | void | Write a global/scene variable. |
hasVar(name) | boolean | Does the variable exist? |
goToScene(nameOrId) | void | Switch scene. |
restartScene() | void | Restart the current scene. |
pause() | void | Pause the game. |
resume() | void | Resume the game. |
save(key, value) | void | Save a value on the device (high scores...). |
load(key) | value | Load a saved value. |
getCamera() | entity|null | The active camera entity. |
spawnParticles(effect, x, y, z, overrides?) | void | Play an effect once at a position: "Sparkles", "Fire", "Smoke", "Explosion", "Dust puff", "Rain", "Confetti", "Magic". overrides e.g. { burst: 50, color: ["#f00", "#ff0"] } |
shakeCamera(intensity, duration) | void | Shake the camera. |
vibrate(ms) | void | Vibrate the phone, e.g. vibrate(40) on a hit (Android; ignored elsewhere). |
on(event, fn) | unsubscribe | Listen: "sceneStart", "collisionStart", "entityCreated", ... |
log(...values) | void | Show a message on screen (debugging). |
input — input
Touch controls and keyboard.
| Member | Type | Description |
|---|---|---|
axis | {x,y} | Joystick / WASD / arrows, each in -1..1. y = forward. |
isDown(name) | boolean | Button or key held, e.g. input.isDown("jump"), input.isDown("Space") |
wasPressed(name) | boolean | Button or key pressed this frame. |
wasReleased(name) | boolean | Button or key released this frame. |
pointer | {x,y,down} | Finger / mouse position in pixels. |
tapped | boolean | A tap happened this frame. |
swipe | "left"|"right"|"up"|"down"|null | Swipe direction this frame. |
tappedEntity | entity|null | Entity under the finger when tapped this frame. |
audio — audio
Sound playback.
| Member | Type | Description |
|---|---|---|
play(nameOrId, {volume, loop, tag}?) | void | Play an audio asset, e.g. audio.play("coin") |
stop(tag?) | void | Stop sounds with a tag (or all). |
setMasterVolume(0..1) | void | Global volume. |
helpers — Helpers
Handy math functions available everywhere.
| Member | Type | Description |
|---|---|---|
lerp(a, b, t) | number | Blend from a to b by t (0..1). |
clamp(v, min, max) | number | Keep v between min and max. |
random(min, max) | number | Random decimal number between min and max. |
randomInt(min, max) | number | Random whole number between min and max (inclusive). |
deg2rad(degrees) | number | Degrees to radians (for Math.sin etc.). |
Globals
| Name | Type | Description |
|---|---|---|
entity | entity | The entity this script is attached to. |
game | game | The game: find/spawn entities, variables, scenes... |
input | input | Joystick, buttons, taps and swipes. |
audio | audio | Play sounds. |
props | object | Values set in the Inspector for this script, e.g. props.speed |
vars | object | Variables storage for this script. |
Vectors
Positions, rotations and scales are {x, y, z} objects:
| Member | Type | Description |
|---|---|---|
x | number | X (right) |
y | number | Y (up) |
z | number | Z (towards the camera; forward is -Z) |
Snippets
The code editor’s Snippets button inserts these ready-made pieces of code.
Move with joystick
Walk around with the on-screen joystick (or WASD / arrow keys).
// Move with the joystick and face the walking direction.
function update(dt) {
const speed = props.speed ?? 5;
const x = input.axis.x;
const y = input.axis.y;
entity.translate(x * speed * dt, 0, -y * speed * dt);
if (x !== 0 || y !== 0) {
entity.rotation.y = Math.atan2(-x, y) * 180 / Math.PI;
}
}
Jump on button
Press the "jump" button to jump. Needs a RigidBody + Collider.
// Jump when the "jump" button is pressed (needs a RigidBody).
function update(dt) {
if (input.wasPressed('jump') && entity.isOnGround()) {
const v = entity.getVelocity();
entity.setVelocity(v.x, props.jumpStrength ?? 7, v.z);
}
}
Spin
Rotate constantly around the up axis.
// Spin around the Y axis.
function update(dt) {
entity.rotate(0, (props.speed ?? 90) * dt, 0);
}
Follow the player
Chase the entity named "Player" and stop when close.
// Chase the Player.
function update(dt) {
const player = game.find('Player');
if (!player) return;
const target = player.getWorldPosition();
entity.lookAt(target.x, entity.position.y, target.z);
if (entity.distanceTo(player) > 1.5) {
entity.moveToward(target.x, entity.position.y, target.z, (props.speed ?? 2) * dt);
}
}
Spawn every second
Create a "Coin" (prefab or object name) near this entity every second.
// Spawn a Coin every second somewhere around this entity.
let timer = 0;
function update(dt) {
timer += dt;
if (timer >= 1) {
timer -= 1;
const p = entity.getWorldPosition();
game.spawn('Coin', { x: p.x + random(-4, 4), y: p.y + 5, z: p.z + random(-4, 4) });
}
}
Collect coin on collision
Put on the Player: touching a Coin destroys it and adds 1 to Score.
// Put this on the Player.
function onCollision(other) {
if (other.name === 'Coin' || other.hasTag('coin')) {
other.destroy();
game.setVar('Score', Number(game.getVar('Score') ?? 0) + 1);
audio.play('coin');
}
}
Change color on tap
Tap the object to cycle through colors.
// Tap this object to change its color.
const colors = ['#ff5c6c', '#ffb547', '#3ecf8e', '#4f8cff', '#a855f7'];
let index = 0;
function onTap() {
index = (index + 1) % colors.length;
entity.setColor(colors[index]);
}
Restart when falling
Restart the scene if this entity falls below the world.
// Restart the level when falling off the map.
function update(dt) {
if (entity.position.y < -10) {
game.restartScene();
}
}
Show score (global)
Global script: keeps a Text entity named "ScoreText" updated.
// Global script: show the Score in a Text entity named "ScoreText".
function update(dt) {
const label = game.find('ScoreText');
if (label) label.setText('Score: ' + game.getVar('Score'));
}
Swipe lanes (runner)
Swipe left/right to switch between 3 lanes, swipe up to jump.
// Endless-runner style lane switching.
let lane = 0; // -1, 0, 1
function update(dt) {
if (input.swipe === 'left') lane = clamp(lane - 1, -1, 1);
if (input.swipe === 'right') lane = clamp(lane + 1, -1, 1);
if (input.swipe === 'up' && entity.isOnGround()) entity.applyImpulse(0, 6, 0);
entity.position.x = lerp(entity.position.x, lane * 2, 10 * dt);
}