Skip to main content

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.

FunctionWhen it runsObject scriptGame 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()).

MemberTypeDescription
idstringUnique id of this entity.
namestringObject type name (clones share it), e.g. "Coin".
tagsSetTags of this entity (read-only set). Use hasTag/addTag.
destroyedbooleanTrue 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
visiblebooleanShow / hide the entity.
enabledbooleanDisabled entities are not updated or drawn.
getVar(name)valueRead an instance variable.
setVar(name, value)voidWrite an instance variable.
hasTag(tag)booleanDoes this entity have the tag? e.g. other.hasTag("enemy")
addTag(tag)voidAdd a tag.
removeTag(tag)voidRemove 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)voidTeleport to a position.
translate(x, y, z)voidMove by an offset in world axes.
moveLocal(x, y, z)voidMove along its own axes (x right, y up, z forward).
setRotation(x, y, z)voidSet rotation in degrees.
rotate(x, y, z)voidRotate by degrees, e.g. entity.rotate(0, 90 * dt, 0)
lookAt(x, y, z)voidTurn to face a world point.
moveToward(x, y, z, distance)voidMove up to distance meters toward a point.
distanceTo(otherOrPoint)numberDistance to another entity or {x,y,z}.
hasBody()booleanHas a RigidBody component?
getVelocity(){x,y,z}Physics velocity (m/s).
setVelocity(x, y, z)voidSet physics velocity.
applyImpulse(x, y, z)voidInstant push, e.g. a jump: applyImpulse(0, 5, 0)
applyForce(x, y, z)voidContinuous push (call every frame).
isOnGround()booleanTrue if a dynamic body rests on something.
setColor(hex)voidChange material color, e.g. setColor("#ff0000")
setOpacity(0..1)voidChange material opacity.
setText(text)voidSet the text of a Text component.
getText()stringGet the text of a Text component.
getUIValue()numberProgress bar value (UI component).
setUIValue(value)voidSet the progress bar value, e.g. health.
getUIMax()numberProgress bar maximum.
setUIMax(max)voidSet the progress bar maximum.
setUIImage(assetName)voidChange the image of a UI element.
setUIColors({ background, text, fill })voidChange UI colors, e.g. { background: "#ff0000" }.
isPressed()booleanTrue while this UI button is held down.
playAnimation(name: string, loop = true)voidPlay a clip of the 3D model, e.g. "walk" or "jump". loop=false plays once and holds the last frame.
stopAnimation()voidStop the playing model animation.
getAnimation()stringName of the playing clip (empty if none).
getAnimationNames()string[]All clip names of the model.
hasAnimation(name: string)booleanTrue if the model has this clip.
setAnimationSpeed(speed: number)void1 = normal, 0.5 = half, 2 = double.
tween(property, to, seconds, ease?)voidAnimate '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?)booleanA tween is running (of that property, or any).
stopTweens()voidStop all tweens where they are.
attachTo(parent)voidCarry this object along with another (keeps its place in the world), e.g. a picked-up key.
detach()voidLet go: back to the top level where it is now.
emitParticles(count: number)voidShoot particles at once from the Particles component, e.g. emitParticles(30) on a hit.
startParticles()voidStart (or restart) the Particles component; also fires its Burst.
stopParticles()voidStop making new particles (the ones out fade normally).
setParticleRate(rate: number)voidParticles per second while emitting.
isEmittingParticles()booleanTrue while the Particles component makes new particles.
getParticleCount()numberParticles currently alive.
playSound()voidPlay this entity's Audio component.
stopSound()voidStop this entity's Audio component.
setBehaviorEnabled(type, on)voidEnable/disable a behavior, e.g. ("platformer", false)
getBehaviorParam(type, param)valueRead a behavior parameter.
setBehaviorParam(type, param, value)voidChange a behavior parameter, e.g. ("platformer", "speed", 8)
getParent()entity|nullParent entity.
getChildren()entity[]Child entities.
destroy()voidRemove the entity (at end of frame).
object3dTHREE.Object3DAdvanced: the underlying three.js object.

game — game​

The running game.

MemberTypeDescription
projectProjectDataThe whole project data (read-only).
sceneSceneDataCurrent scene data (read-only).
timenumberSeconds since the scene started.
dtnumberLast frame time in seconds.
timeScalenumberGame speed: 1 normal, 0.5 slow motion.
pausedbooleanIs the game paused?
inputinputSame as input.
audioaudioSame as audio.
screen{width,height}Screen size in pixels.
select(selector)entity[]All entities by name or #tag: game.select("#enemy")
find(nameOrId)entity|nullFirst entity with that name/id: game.find("Player")
getAllEntities()entity[]Every live entity.
spawn(name, position?, rotation?)entity|nullCreate a prefab / clone: game.spawn("Coin", {x:0,y:5,z:0})
destroy(entity)voidDestroy an entity.
pick(screenX, screenY)entity|nullEntity at a screen point.
hasLineOfSight(a, b)booleanTrue when nothing solid is between the two objects, e.g. an enemy can see the player.
raycast(from, to){entity,point,distance}|nullPhysics ray between two world points.
isTouching(a, b)booleanAre two entities touching?
getVar(name)valueRead a global/scene variable: game.getVar("Score")
setVar(name, value)voidWrite a global/scene variable.
hasVar(name)booleanDoes the variable exist?
goToScene(nameOrId)voidSwitch scene.
restartScene()voidRestart the current scene.
pause()voidPause the game.
resume()voidResume the game.
save(key, value)voidSave a value on the device (high scores...).
load(key)valueLoad a saved value.
getCamera()entity|nullThe active camera entity.
spawnParticles(effect, x, y, z, overrides?)voidPlay 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)voidShake the camera.
vibrate(ms)voidVibrate the phone, e.g. vibrate(40) on a hit (Android; ignored elsewhere).
on(event, fn)unsubscribeListen: "sceneStart", "collisionStart", "entityCreated", ...
log(...values)voidShow a message on screen (debugging).

input — input​

Touch controls and keyboard.

MemberTypeDescription
axis{x,y}Joystick / WASD / arrows, each in -1..1. y = forward.
isDown(name)booleanButton or key held, e.g. input.isDown("jump"), input.isDown("Space")
wasPressed(name)booleanButton or key pressed this frame.
wasReleased(name)booleanButton or key released this frame.
pointer{x,y,down}Finger / mouse position in pixels.
tappedbooleanA tap happened this frame.
swipe"left"|"right"|"up"|"down"|nullSwipe direction this frame.
tappedEntityentity|nullEntity under the finger when tapped this frame.

audio — audio​

Sound playback.

MemberTypeDescription
play(nameOrId, {volume, loop, tag}?)voidPlay an audio asset, e.g. audio.play("coin")
stop(tag?)voidStop sounds with a tag (or all).
setMasterVolume(0..1)voidGlobal volume.

helpers — Helpers​

Handy math functions available everywhere.

MemberTypeDescription
lerp(a, b, t)numberBlend from a to b by t (0..1).
clamp(v, min, max)numberKeep v between min and max.
random(min, max)numberRandom decimal number between min and max.
randomInt(min, max)numberRandom whole number between min and max (inclusive).
deg2rad(degrees)numberDegrees to radians (for Math.sin etc.).

Globals​

NameTypeDescription
entityentityThe entity this script is attached to.
gamegameThe game: find/spawn entities, variables, scenes...
inputinputJoystick, buttons, taps and swipes.
audioaudioPlay sounds.
propsobjectValues set in the Inspector for this script, e.g. props.speed
varsobjectVariables storage for this script.

Vectors​

Positions, rotations and scales are {x, y, z} objects:

MemberTypeDescription
xnumberX (right)
ynumberY (up)
znumberZ (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);
}