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.✔
fixedUpdate(dt)Called on every physics step (60 a second), whatever the frame rate. dt is always 1/60.✔✔
onEnable()The object is switched on: before start(), and each time it is enabled again.✔✔
onDisable()The object is switched off or about to be destroyed.✔✔
onTriggerEnter(other, collision)This entity entered, or was entered by, a trigger other.✔
onTriggerStay(other, collision)Every frame while it overlaps a trigger other.✔
onTriggerExit(other, collision)This entity left a trigger other.✔
onCollision(other, collision)This entity started touching other. collision has the details: contacts, point, normal, impulse, relativeVelocity, speed, isTrigger.✔
onCollisionStay(other, collision)Every frame while it touches other (only define it if you need it: it reads every contact).✔
onCollisionEnd(other, collision)This entity stopped touching other.✔
onParticleCollision(other, events)Particles hit other (Collision module with Send Collision Messages). Called on the system's object and on the one hit. events: [{ intersection, normal, velocity, other }].✔
onParticleTrigger(events)Particles met the Triggers module's colliders (actions set to Callback). events: [{ type: "inside" | "outside" | "enter" | "exit", particles }].✔
onParticleSystemStopped()Its Particle System stopped and the last particle died (Stop Action: Callback).✔
onTap()The player tapped this entity.✔
onClick()This UI button was clicked.✔
onValueChanged(value)This slider moved (a number), toggle switched (true / false), dropdown option was picked (its index) or input field was typed in (its text).✔
onSubmit(text)Enter was pressed in this Input Field; text is what was typed.✔
onEndEdit(text)The player stopped typing in this Input Field (Enter, a tap elsewhere, Esc or B).✔
onHTMLClick(id, target)Something inside this HTML element was clicked. id is the id of the clicked part or the nearest one around it (empty if none); target is the element clicked.✔
onHTMLChange(id, value, target)A form part inside this HTML element changed (a text box left, a box ticked, a list picked). value: the text, 1 / 0 for a checkbox, a number for a number or range input.✔
onPointerDown(event)The player pressed this UI element (needs Raycast Target). event: { x, y, entity }.✔
onPointerUp(event)The player let go of this UI element without dragging it.✔
onPointerEnter(event)A mouse moved onto this UI element (touch screens have no hover).✔
onPointerExit(event)A mouse moved off this UI element.✔
onLongPress(event)The player held this UI element for half a second without moving.✔
onBeginDrag(event)The player started dragging this UI element (moved more than a few pixels).✔
onDrag(event)Every move while dragging. event.delta = [dx, dy] since the last one, in the element's reference px with Y up: add it to component('ui').anchoredPosition to follow the finger.✔
onEndDrag(event)The player let go after dragging this UI element.✔
onDrop(event)Something was dropped on this UI element. event.dragged is the element that was dragged; event.entity is this one.✔
onArrived()It reached the point of entity.moveTo() (or got as close as it could).✔
onCurveEnd()This entity (with Follow curve) reached the end of its curve: each time round when it loops, each end when it ping-pongs.✔
onDestroy()This entity is about to be destroyed.✔
onGameSaved(slot)The game was saved in a slot (game.saveGame / the Save game block): show a "Saved" message.✔
onGameLoaded(slot)A saved game came back. start() has run on the rebuilt scene; the object's variables and position are the saved ones, so read them here. What the save does not hold (the music, a script's own lets) is set up here.✔

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.
layerstringThe layer the object is on ("Default" unless changed; Project settings → Layers). Writable: entity.layer = "Water". Cameras can leave layers out (Draw switches); game.raycast takes layers.
persistbooleanTrue: the object stays when the game goes to another scene (with its children, position and variables) instead of being made again. An object of the same name in the next scene that also has persist on is replaced by it, never doubled. Also the "Keep across scenes" switch in the inspector.
destroyedbooleanTrue once the entity has been destroyed.
drawsLayer(layer)booleanA camera: true while it draws objects on this layer (its Draw <layer> switch). False on an object without a camera.
setDrawLayer(layer, draw)voidA camera: draw objects on this layer (true) or leave them out (false), e.g. minimapCam.setDrawLayer("Icons", true). Works on the main camera and on render-texture cameras.
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.
setSpin(x, y, z)voidSet how fast it spins, in degrees per second around the world X, Y and Z axes.
applyImpulse(x, y, z)voidInstant push, e.g. a jump: applyImpulse(0, 5, 0)
breakJoint(index?: number)voidCut this object's Joint components, or the one at index (0 = the first): a rope snaps, a door is torn off.
setJointMotor(speed: number, force?: number, index?: number)voidDrive its hinge, slider or wheel Joints: degrees per second (metres per second for a slider), positive = counter-clockwise; force = the most it pushes.
stopJointMotor(index?: number)voidTurn the joint motor off: it turns or slides freely again.
getJointAngle(index?: number)numberHinge: angle in degrees from where it started; slider: metres moved.
getJointSpeed(index?: number)numberHinge / wheel: turning speed in degrees per second; slider: metres per second.
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.
setUniform(name, value)booleanSet a setting (uniform) of this object's custom shader while the game runs: a number, or a colour as text. entity.setUniform("uAmount", 0.7). Only this object changes; false when its shader has no such uniform.
setRenderTexture(name)booleanShow a render texture (Files) as this object's picture: its surfaces, sprite, or UI Image. tv.setRenderTexture("Cam B"); null puts its own picture back. False when it has nothing that can show one.
setText(text)voidSet the text of a Text component.
getText()stringGet the text of a Text component.
getUIValue()numberSlider (or bar) value (UI component).
setUIValue(value)voidSet the slider value, e.g. health.
getUIMax()numberSlider maximum.
setUIMax(max)voidSet the slider maximum.
getUIMin()numberSlider minimum.
setUIMin(min)voidSet the slider minimum.
setUIImage(assetName)voidChange the image of a UI element.
setUIFont(assetName)voidChange the font of a UI element's text ('' = the default font).
setUIColors({ background, text, fill })voidChange UI colors, e.g. { background: "#ff0000" }.
setUIInteractable(on)voidGrey a button or slider out, or turn it back on (Interactable).
selectUI()voidChoose this button or slider for the controller and arrow keys, e.g. when a menu opens (Unity Select()).
isUISelected()booleanIs this button or slider the one the controller or arrow keys have chosen?
focusUI()voidInput Field: start typing in it. Read and set what is typed with getText() / setText().
isUIFocused()booleanInput Field: is the player typing in it right now?
isToggleOn()booleanToggle: is it on (ticked)?
setToggleOn(on: boolean)voidToggle: switch it as a click would. Its Toggle group turns the others off, and On value changed runs.
getUIOptions()string[]Dropdown: its options' texts. getUIValue() is the chosen one's index, getText() its text.
setUIOptions(options: string[])voidDropdown: replace its options (a resolution list, save slots).
addUIOption(text: string)voidDropdown: add an option at the end.
htmlRootShadowRoot | nullHTML element: the shadow root its markup is drawn in, e.g. entity.htmlRoot.querySelector("#name").value or .addEventListener("input", …).
setHTML(html: string)voidHTML element: replace all its markup (the CSS stays).
getUIPosition(){x, y}Where a UI element sits: its anchored position in canvas pixels from its anchor.
setUIPosition(x, y)voidMove a UI element to this anchored position (canvas px). Leave an axis out (undefined) to keep it.
isUI()booleanIs this object a UI element (has a Rect Transform)?
getUIScreenPosition(){x, y}Where the pivot of a UI element is drawn, in canvas px from the bottom-left (Unity transform.position). Use it to line two elements up, whatever their parents.
getUICenter(){x, y}Where the middle of a UI element box is drawn (same space as getUIScreenPosition). Differs from the pivot when the pivot is not in the centre.
setUIScreenPosition(x, y)voidPut the pivot of a UI element at a canvas position. Leave an axis out (undefined) to keep it.
getUISize(){x, y}Size of a UI element (sizeDelta).
setUISize(width, height)voidSet a UI element's width and height. Leave one out (undefined) to keep it.
setUIAnchors(minX, minY, maxX, maxY)voidAnchors as fractions of the parent (0,0 is bottom-left). Same corner: fixed size; apart: stretch.
setUIPivot(x, y)voidThe point of the element that its position, rotation and scale refer to, as a fraction of its own box.
moveUITo(target, offsetX, offsetY)voidPut this UI element's pivot on the middle of another UI element, plus an offset in canvas px. attachTo(parent) / detach() also work for UI elements and move them inside the new parent.
refreshUI()voidRe-apply the UI styles after writing component data directly.
isPressed()booleanTrue while this UI button is held down.
playAnimation(name: string, loop = true)voidPlay a clip of the 3D model, or an animation of a sprite, e.g. "walk" or "jump". loop=false plays once and holds the last frame. Asking for the clip already playing keeps it going. With an Animator component the name is a state of its controller.
animatorAnimator|nullThe Animator (an Animator component with a controller), as in Unity: animator.setFloat("Speed", 3), setBool, setInteger, setTrigger("Attack"), resetTrigger, getFloat / getBool / getInteger, play("Die"), crossFade("Run", 0.2), state, isInState("Jump"), normalizedTime(), isInTransition(), setLayerWeight(1, 0.5), speed. Null without one.
stopAnimation()voidStop the playing model animation.
isMinebooleanIn a multiplayer room: true when this player drives the object (placed objects belong to the host, objects from game.net.spawn to whoever spawned them). Always true outside a room. Objects driven by someone else do not run their behaviors; check isMine before reading input in your own scripts.
ownerNetPlayer|nullIn a multiplayer room: the player who drives the object, or null.
ragdoll(on = true, opts?)voidMake a rigged 3D character limp with physics, e.g. entity.ragdoll() when it dies; ragdoll(false) brings it back to its animation. The object itself stays where it is, only its bones move. entity.ragdolled says whether it is limp. entity.ragdoll(true, { impulse: { x, y, z } }) starts it with a shove (a hit that knocks it down).
ragdollPower(power)voidPowered ragdoll: how hard the ragdoll's bones are pulled toward the playing animation, 0 (limp) to 1 (follows it, a hit still moves it and it recovers). entity.ragdoll(true, { power: 0.8 }) starts powered: the character keeps animating and keeps its own body, so it still walks.
ragdollPush(bone, x, y, z)voidPush the limp character's bones whose name contains bone (e.g. "arm", "head"), an impulse shared out by their mass.
getAnimation()stringName of the playing clip (empty if none).
isAnimationBusy()booleanTrue while a play-once animation (loop off) is still running.
getAnimationNames()string[]All clip names of the model, or the animations of a sprite.
hasAnimation(name: string)booleanTrue if the model (or sprite) has this clip.
setAnimationSpeed(speed: number)void1 = normal, 0.5 = half, 2 = double.
setSpriteFrame(frame: number)voidSprite: show one frame (0 = the first) and stop its animation. playAnimation() plays again.
setSpritePart(layer: string, label: string)voidSprite drawn in layers: show another picture on a layer, e.g. setSpritePart("Face", "Angry") (Unity's Sprite Resolver).
getSpritePart(layer: string)stringSprite drawn in layers: the label of the picture a layer shows.
getSpriteFrame()numberSprite: the frame being shown (0 = the first).
getSpriteFrameCount()numberSprite: how many frames it has.
setTile(x: number, y: number, tile: number)voidTilemap: paint one cell (counted in tiles, y up) with a tile (0 = the first of the sheet). A negative tile erases it.
getTile(x: number, y: number)numberTilemap: the tile in a cell, or -1 when it is empty.
removeTile(x: number, y: number)voidTilemap: erase a cell.
cellAt(worldX: number, worldY: number){ x, y }Tilemap: the cell at a world position.
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.
morphTargetsstring[]Model: the names of its morph targets (blend shapes), e.g. ["Smile", "Blink"]. Empty while it loads or when it has none.
setMorph(name, value, seconds?)booleanModel: bend a morph target, 0 to 1, at once or blended over seconds, e.g. setMorph("Smile", 1, 0.3). false when the model has none of that name.
setVolumeWeight(weight, seconds?)booleanPost-processing Volume: set how much of it counts, 0 to 1, at once or gliding there over seconds, e.g. setVolumeWeight(0, 1.5). false when the object has no Volume component.
getMorph(name)numberModel: how far a morph target is applied, 0 to 1.
video{play,pause,restart,playing}|nullThe video on this object (its material's Video): video.play(), video.pause(), video.restart(), video.playing. Null when it shows no video.
attachTo(parent, part?)voidCarry this object along with another (keeps its place in the world), e.g. a picked-up key. part: the name of a part of the 3D model of the other object, such as a hand bone.
detach()voidLet go: back to the top level where it is now.
particleSystemParticleSystem|nullThe Particle System (like Unity's): every module live — particleSystem.main.startSpeed = 8, particleSystem.noise.enabled = true — plus play(), pause(), stop(), emit(count, params), simulate(t), getParticles() / setParticles(). Null without a Particles component.
lineRendererLineRenderer|nullThe Line Renderer (like Unity's): its settings live — lineRenderer.loop = true, lineRenderer.width.scale = 0.05 — plus setPosition(i, v), setPositions([...]), getPosition(i), getPositions() and positionCount. Null without a Line renderer component.
trailRendererTrailRenderer|nullThe Trail Renderer (like Unity's): its settings live — trailRenderer.emitting = false, trailRenderer.time = 0.2, trailRenderer.width.scale = 0.5 — plus clear(), positionCount, getPosition(i), getPositions(), addPosition(v). Null without a Trail renderer component.
emitParticles(count: number)voidShoot particles at once from the Particle System, e.g. emitParticles(30) on a hit.
startParticles()voidPlay the Particle System (bursts at time 0 go out). Safe to call every frame: already playing means nothing changes.
restartParticles()voidPlay the Particle System from the beginning even if it is already playing.
stopParticles(clear?: boolean)voidStop making new particles; the ones out finish their life, or go at once with stopParticles(true).
setParticleRate(rate: number)voidEmission rate over time (particles per second).
isEmittingParticles()booleanTrue while the Particle System makes new particles.
getParticleCount()numberParticles currently alive.
makeLiveCamera()voidVirtual Camera: become the live one (switched on, Priority raised above the others); the main camera blends over with its Blend In. Its settings: component("virtualCamera"), e.g. .follow = player.id, .priority = 20.
canSee(target, opts?)booleanCan it see the target: inside its Sight cone (Range, View Angle from its eye; or opts { range, angle }) with nothing solid in between. E.g. if (guard.canSee(player)) …
directorTimelineAPI | nullPlayable Director: the timeline it plays (play, pause, stop, skip, seek, time, isPlaying…); play() uses the Wrap Mode of the director. E.g. door.director.play().
isLiveCamerabooleanVirtual Camera: true while it is the one moving the main camera.
resetCloth()voidCloth: every point back on the plane, hanging still. Its settings are component("cloth"), e.g. component("cloth").windScale = 2.
playSound()voidPlay this entity's Audio component.
stopSound(fadeOut = 0)voidStop the sound of its Sound component, fading out over fadeOut seconds.
getComponent(type)object|nullA copy of a component's or behavior's settings, e.g. getComponent("rigidbody").mass. Read-only — component() gives you the live one.
component(type)component|nullA component as a live object: every setting in the Inspector is a property you can read and write, e.g. component("rigidbody").mass = 5, component("light").intensity = 2. Structural ones (shape, model) need rebuild() — component(type).set({ … }) does it for you.
getComponents()string[]Component types on this object.
addComponent(type, settings?)component|nullAdd a component and rebuild, e.g. addComponent("rigidbody", { mass: 2 }). Types: mesh, collider, rigidbody, light, camera, text, ui, audio, particles, terrain, water, sprite.
removeComponent(type)booleanRemove a component and rebuild.
rebuild()voidRebuild the object from its components (3D content, body, text, UI, particles, behaviors), keeping where it is and its variables.
hasComponent(type)booleanDoes it have this component or behavior? e.g. other.hasComponent("health")
getScript(name)script|nullA code script on this object, live: what it exports (its fields among them), e.g. other.getScript("Enemy")?.hit(1), .hp = 5. In that script: export function hit(n) { … }, export let hp = 3.
behavior(type)behavior|nullA behavior as a live object: its settings are properties (behavior("platformer").speed = 8) and it has its own readings and methods, e.g. behavior("car").speed, behavior("platformer").jump(), behavior("health").health. Null without that behavior.
getBehaviors()string[]Behavior types on this object.
addBehavior(type, params?)behavior|nullAdd a behavior and start it now, e.g. addBehavior("bullet", { speed: 20 })
removeBehavior(type)booleanStop and remove a behavior.
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)
damage(amount, from?)voidHealth behavior: lose health; from = what hit it (for Knockback). Fires On hurt / On death.
heal(amount)voidHealth behavior: get health back, up to Max health. Current health: getVar("health").
moveTo(x, z, speed?, options?)voidWalk to a point on the ground (default speed 3, around walls), playing walk / idle clips. onArrived() runs there. options: { avoidWalls: false, animate: false, sprintSpeed: 8 }
stopMoving()voidCancel moveTo().
movingTobooleanA moveTo() is under way.
inWaterbooleanIn a Water object (a physics body: any part of it).
enterVehicle(vehicle)voidGet into a Boat or Car: ride in its seat; cameras follow it. It does not steer it: pass the input in with driveCar / setMoveInput.
exitVehicle()voidGet out, beside the vehicle (on land if possible).
driveCar(steer, gas, brake)voidDrive a Car this frame: steer −1 (left) … 1 (right), gas and brake 0 … 1. Call it every frame the controls are held; calls in one frame merge, so steering and gas from two places both arrive.
setMoveInput(x, y)voidMove a Platformer, Top-down or Boat this frame: right/left (x) and forward/back (y), −1 … 1. Call it every frame the input is held; calls in one frame merge.
simulateControl(...controls)voidPress controls for this frame, like a key would: "left", "right", "up" (gas / forward), "down" (brake / reverse), "jump", "handbrake". Several at once: simulateControl("left", "up"). Works on Platformer, Top-down, Car and Boat.
vehicleentity|nullThe vehicle it is riding, or null.
hasDriverbooleanA boat or car someone got into (Enter vehicle).
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?
loadingProgressnumberOn a loading screen: how far it got, 0 … 1 (assets loaded and time held, whichever is further behind). Draw a loading bar with it; the game moves on when it reaches 1.
isLoadingbooleanA loading screen is up and the game has not moved on yet.
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")
query(selector)EntitySetPick objects Construct-style, chained: game.query("Enemy").withVar("hp", "<", 10).nearest(player).first(). Steps: where, withTag, withVar, within, nearest, farthest, sortBy, take, each, map, some; read with first, last, nth, random, toArray, length. Each step returns a new set.
first(selector)entity|nullFirst live entity matching a selector: game.first("#enemy")
getAllEntities()entity[]Every live entity.
spawn(name, position?, rotation?, parent?)entity|nullCreate a prefab / clone: game.spawn("Coin", {x:0,y:5,z:0}). With a parent it is created inside it (a row in a list): game.spawn("Row", undefined, undefined, list)
create(spec?)entity|nullMake a brand-new object other scripts and event sheets can find: game.create({name:"Portal", shape:"torus", position:{x:0,y:2,z:0}, color:"#8f6fff"}). Put your own three.js meshes inside its .object3d.
destroy(entity)voidDestroy an entity.
pick(screenX, screenY)entity|nullEntity at a screen point.
touchWorld(){x,y,z}The spot in the world under the finger / mouse (a surface, else the ground plane). Tap to move: player.moveTo(p.x, p.z).
watchSight(target)voidFire "seen" / "lostSight" events when a Sight object starts / stops seeing objects with this name (or "#tag"). E.g. game.watchSight("Player"); game.on("seen", (e) => …)
hasLineOfSight(a, b)booleanTrue when nothing solid is between the two objects, e.g. an enemy can see the player.
raycast(from, to | { direction, length, tags?, layers?, ignore?, includeMoving? }, options?){entity,point,normal,distance}|nullPhysics ray between two points, or along a direction: game.raycast(p, { direction: {x:0,y:-1,z:0}, length: 5, tags: ["ground"], ignore: player }). Triggers never block it.
isTouching(a, b)booleanAre two entities touching?
touchInfo(a, b)CollisionInfo | nullCurrent contact of two touching entities (point, normal, speed, impulse), or null
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.
saveGame(slot?)booleanSave the whole game in a named slot on the device: the scene, every variable and every object as it is now (position, variables, health, text, animation). game.saveGame("mysave"); false when storage is full. Scripts hear onGameSaved(slot).
loadGame(slot?)booleanBring a saved game back after this tick: the saved scene is rebuilt as it was. Its start() / On start of scene do not run again; onGameLoaded(slot) and "On game loaded" do, so set up there what the save does not hold (music, script locals). False when nothing is saved there ("loadFailed").
hasSaveGame(slot?)booleanIs there a saved game in the slot? Show a Continue button when there is.
deleteSaveGame(slot?)voidRemove a saved game from the device.
table(name)tableA data table made in Files: game.table("Item").get("Sword"), .all(), .where(r => r.damage > 5), .ids(), .has(name), .length.
languagestringCurrent language code from Files → Localization ("en", "fr"). Set it to switch: every object with a text key changes, and it is remembered. game.languages lists the codes.
t(key, ...args)stringA text from Files → Localization in the current language; {0}, {1} in it are filled by the arguments: game.t("score", points). game.on("languageChanged", …) tells when it changes.
navmeshNavMeshThe baked navigation mesh (Project settings → Navigation): game.navmesh.findPath(from, to, { radius, height }) gives { complete, points: [{x,y,z,leap}] } over slopes, stairs and floors; sample(point) the nearest place to stand; rebuild() after walls change; enabled, lastBakeMs.
steamSteamAPISteam in a Windows build made with a Steam App ID (steam_api64.dll next to the .exe); elsewhere game.steam.available is false and the calls do nothing. Files → Services achievements and leaderboards reach Steam by themselves. game.steam.userName, .language, .ownsDlc(appId), .setStat("kills", 12), await .getStat("kills"), .submitScore("Best", 900), .setRichPresence("status", "In the forest"), .overlayOpen (pause while true), .openOverlay("achievements").
servicesServicesAPIAchievements, leaderboards, ads and purchases from Files → Services: game.services.unlockAchievement("first"), .submitScore("score", 12), .showRewarded(), .buy("noAds"), .owns("noAds"). Set game.services.provider = { showRewarded: () => …, buy: p => … } to handle any of them yourself (your own ad network or store); the results come back as game.on("adFinished" / "purchaseFinished" / "achievementUnlocked", …).
httpHttpAPIWeb requests: const r = await game.http.get("https://…"); r.ok, r.status, r.json, r.text. Also .post(url, body) (an object is sent as JSON) and .request(url, { method, headers, body, timeout, name }). It never throws: a failure is r.ok === false with r.error. https only (Project settings → Web requests → Allow HTTP for plain http); a game played from the gallery may only contact the domains listed there. Replies also come as game.on("webResponse" / "webError", …).
netNetAPIRooms for realtime multiplayer: const r = await game.net.create(); r.code is the room code to share; a friend does await game.net.join(code). Then game.net.send("move", { x: 1 }) reaches the others, and game.on("netMessage", m => m.name, m.data, m.from.name) receives. game.net.players, .me, .host, .isHost, .code. Also "netPlayerJoined" / "netPlayerLeft" / "netClosed". A dropped connection gets back into the same seat by itself ("netReconnecting", then "netReconnected"; "netClosed" if it cannot). The room only relays messages (it never runs your game): each player moves their own objects and sends where they are; the host decides shared things like the score. Up to 8 players, 30 messages a second each, about 2000 characters a message. game.net.spawn("Car", { x, y, z }) makes a prefab that every player sees: you drive it, the others see a copy that glides along (give prefabs and placed objects a Net Sync component to choose what is sent). game.net.setShared("round", 3) / addShared("score", 1) / getShared("round") are values the whole room shares and remembers (a late joiner gets them; game.on("netShared", e => e.name, e.value) fires on each change, and once per value when you join). game.net.quickMatch() joins the fullest open room or makes a public one; game.net.listRooms() lists the open ones; create({ public: true, title }) lists yours. entity.claim() takes control of a synced object. entity.isMine says whether this player drives an object (a placed object belongs to the host); only run input on objects that are yours.
timeline(name)TimelineA cutscene made in Files → Timeline: game.timeline("Intro").play(). Also pause(), stop(), skip() (the signals still to come fire), seek(seconds), time, duration, isPlaying, finished, speed, loop. game.on("timelineSignal", e => …) hears its signals (e.signal), "timelineFinished" its end.
windAt(x, y, z){x,y,z}The wind of every Wind Zone at a world point (m/s², pulses and gusts included): make a flag, sail or tree sway with it.
renderTexture(name)RenderTextureA render texture made in Files (what a camera with it as Target Texture draws): game.renderTexture("Monitor").paused = true freezes the picture, false starts it again; refresh() draws one more picture even while paused; name, width, height.
getCamera()entity|nullThe active camera entity.
three{renderer,scene,camera}Advanced: the three.js renderer, scene and camera behind the game, e.g. game.three.scene.add(mesh).
rapier{RAPIER,world,gravity,…}Advanced: the physics engine behind the game. game.rapier.world is the Rapier World, game.rapier.bodyOf(entity) / collidersOf(entity) its objects, game.rapier.setGravity(x, y, z) the world gravity. Use it with RAPIER.
spawnParticles(effect, x, y, z, overrides?)voidPlay an effect once at a position: "Sparkles", "Fire", "Smoke", "Explosion", "Dust puff", "Rain", "Confetti", "Splash", "Bubbles", "Magic". overrides change any module, e.g. { main: { startColor: "#ff0000" }, noise: { enabled: true } }
shakeCamera(intensity, duration, from?, radius?)voidShake the camera. With from (a position, e.g. bomb.position) it is an impulse: weaker the farther the camera is, nothing past radius (default 20 m).
liveCamera()RuntimeEntity | nullThe live Virtual Camera (the one moving the main camera), or null.
debug{drawLine,drawRay,drawSphere,drawCircle,drawBox,drawPoint,clear}Draw shapes over the game to check positions and sizes, like Unity Debug.DrawLine and Gizmos: game.debug.drawSphere(enemy.position, 5, "#ff0000"), drawLine(a, b, color, seconds), drawRay(origin, direction), drawCircle(center, radius), drawBox(center, size), drawPoint(position). Seconds default to 0 = one frame, so call it every update().
quality{level,pixelRatio,shadows,shadowMapSize,shadowDistance,cascades,shadowmaskMode,glow,depthOfField,occlusion,edgeSmoothing,colorFinish,mirrors,glass,lensFlares,effects,antialias,maxParticles,detailDensity}Graphics quality, like Unity QualitySettings: game.quality.level = "low" applies one of the quality levels of the project (Project settings, Graphics: Low, Medium and High to start with, add your own), by its id, its name or its position, and resets the single settings; game.quality.level reads the id of the level in force; the single ones change just that: pixelRatio (1), shadows, shadowMapSize (512, 1024, 2048), shadowDistance (meters sun shadows reach, cascades too, 5 to 200: shorter is sharper), cascades (0, 2, 3, 4), shadowmaskMode ("distanceShadowmask" or "shadowmask", for scenes baked with Lighting Mode Shadowmask), mirrors (picture size, 0 = plain metal), glass, lensFlares, maxParticles, detailDensity (share 0 to 1 of the painted terrain grass and details drawn), and which screen effects are allowed: glow, depthOfField, occlusion, edgeSmoothing, colorFinish (effects = all of them at once). Saved on the device. antialias counts from the next start. A quality level only forbids effects a scene has, it never adds any.
effects{vignette,fringe,saturation,contrast,glow,depthOfField,occlusion,fxaa,...}The screen effects in force (from the Post-processing Volumes), live: game.effects.vignette = 0.6, game.effects.focusDistance = 4, game.effects.glow = true; numbers: vignette, fringe, saturation, contrast, glowStrength, glowSpread, glowThreshold, focusDistance, blurAmount, blurLimit, occlusionSize, occlusionStrength (kept inside the editor ranges); switches: fxaa, glow, depthOfField, occlusion; game.effects.focusObject = "Player" keeps that object in focus ("" = back to focusDistance). game.effects.set("vignette", 0.8, 2) glides there over 2 seconds. Your changes sit on top of the volumes and a new scene starts clean. To change a volume itself: entity.component("volume").weight = 0.5 or .profile = "Underwater" (a profile name). Switching an effect on needs a game that can draw effects: the volumes have a profile with one, or Project settings → Effects from scripts and events is on. The quality level can still forbid an effect.
addDecal(at, normal, options?)booleanStick a picture on a surface, like a bullet hole: game.addDecal(hit.point, hit.normal, { image: "bulletHole", size: 0.3 }). image is bulletHole, splat, scorch, crack, footprint or the name of an image in Files; also color, lifetime (seconds, 20; 0 stays) and roll. Returns false when no surface is there.
vibrate(ms)voidVibrate the phone, e.g. vibrate(40) on a hit (Android; ignored elsewhere).
enterFullscreen()Promise<void>Fill the screen. Browsers only allow it inside a tap, so call it from a Button's On Click.
exitFullscreen()Promise<void>Leave fullscreen.
quit()voidClose the game: the window of a Windows build or the Android app. A play-test in the editor stops.
lockOrientation(mode?)Promise<void>Keep the screen 'landscape' or 'portrait'. 'project' (default) uses the project setting, 'free' lets it rotate. Call from a tap.
on(event, fn)unsubscribeListen: "sceneStart", "collisionStart", "entityCreated", "waterEnter", "seen", ...
after(seconds, fn, owner?)cancelRun fn once after a delay of game time. In a script, plain after(seconds, fn) belongs to the object of the script already; this one takes the object to belong to, or none.
every(seconds, fn, owner?)stopRun fn every so many seconds of game time until the function it returns is called. In a script, plain every(seconds, fn) belongs to the object of the script already.
eventsmessagesMessages between scripts: game.events.on("coinTaken", (n) => …, entity), game.events.once(…), game.events.emit("coinTaken", 3). Listeners end with the scene; with an owner object they end when it is destroyed and wait while it is disabled.
log(...values)voidShow a message on screen and in the Play console (debugging).
consoleLog(...values)voidWrite a line to the Play console only, nothing on screen. console.log() in a script does the same.

input — input​

Touch controls and keyboard.

MemberTypeDescription
axis{x,y}Joystick / WASD / arrows / gamepad stick, each in -1..1. y = forward.
look{x,y}Look this frame in degrees: locked mouse, gamepad right stick or a drag. x = right, y = up.
gamepadbooleanA gamepad has been used. Its buttons work as keys: "PadA", "PadB", "PadX", "PadY", "PadLB", "PadRB", "PadLT", "PadRT", "PadStart".
devicestringWhat the player used last: "gamepad", "keyboard" (keys or mouse) or "touch". Show button prompts for it.
deviceChangedbooleanTrue for the one frame the device changes: update button prompts then.
padStylestringWhose button names gamepad prompts show: "xbox", "playstation" (✕ ○ □ △), "switch" or "deck". From the gamepad in use.
setPadStyle(style)voidForce a gamepad prompt style, or "auto" to follow the gamepad again.
padStyleChangedbooleanTrue for the one frame the prompt style changes.
prompt(action, device?)stringThe button prompt for a control button on the device in use: "Space", "A", "WASD" for "move". In UI text, <prompt=jump> draws it as a key cap or a gamepad button.
rebind(action, device?)Promise<boolean>Wait for the player to press a new key (or gamepad button) for a control button or "moveUp"/"moveDown"/"moveLeft"/"moveRight". Escape cancels. Kept on this device.
rebindingstring|nullThe action waiting for a key, or null.
reboundstring|nullThe action rebound this frame, or null.
cancelRebind()voidStop waiting for a key.
bindingOf(action){keys, pads, pad}The keys and gamepad buttons an action has now (pad = the first).
setBinding(action, {keys?, pads?})voidGive an action these keys / gamepad buttons (kept on this device).
resetBindings(action?)voidBack to the game's own controls: one action, or all.
isDown(name)booleanButton, key or gamepad button held, e.g. input.isDown("jump"), input.isDown("Space"), input.isDown("PadA")
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, group, pitch, fadeIn}?)SoundHandlePlay an audio asset, e.g. audio.play("coin") or audio.play(hit) with a sound field. Returns its handle: handle.stop(fadeOut), handle.fadeTo(volume, seconds), handle.volume, handle.pitch, handle.playing.
stop(tag?, fadeOut?)voidStop sounds with a tag (or all), fading out over fadeOut seconds.
isPlaying(tag?)booleanA sound with that tag (or any) is playing.
playMusic(nameOrId, {volume, fade, group, loop, sync}?)voidPlay music, cross-fading from the track playing (fade defaults to 1 s). Asking for the same track only changes its volume. sync: "bar" or "beat" starts it on the next bar / beat of the music playing.
stopMusic(fade = 1)voidFade the music out.
setMusicLayer(layer, volume, fade = 1)voidAdaptive music: fade a layer of the music (a beat made with layers) to a volume, 0 … 1. It stays so until changed.
getMusicLayer(layer)numberThe volume of a music layer (1 unless changed).
musicBeatnumberBeats since the music started (0, 1, 2 …; 4 to a bar), -1 when no music with a tempo plays (a beat, or a sound given a tempo in Files).
musicBarnumberBars since the music started, -1 when none.
musicTimenumberSeconds into the music playing.
musicBpmnumberThe music’s tempo (0 when unknown).
musicstringName of the music playing, or "".
setGroupVolume(group, 0..1, fade?)voidVolume of a mixer group (Project settings → Audio mixer), smoothly over fade seconds. "Master" is the master volume.
getGroupVolume(group)numberVolume of a mixer group.
setGroupMuted(group, muted)voidSilence a mixer group, or bring it back.
setGroupLowpass(group, hz, fade?)voidMuffle a mixer group (e.g. 600 under water); 0 turns the filter off.
setMasterVolume(0..1)voidGlobal volume.
getMasterVolume()numberGlobal volume.
pauseAll()voidPause every sound (a pause menu).
resumeAll()voidCarry on where they were.
pausedbooleanSounds are paused.

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.).
wait(seconds)PromiseCarry on later, in an async function: async function start() { await wait(2); entity.destroy(); }. Game time: it waits while paused and follows timeScale. If the object is destroyed first, the function stops there.
after(seconds, fn)cancelRun fn once after a delay, e.g. after(2, () => entity.destroy()). Game time (pause and timeScale count). Returns a function that cancels it; dropped when this object is destroyed.
every(seconds, fn)stopRun fn again and again, e.g. every(1, () => game.spawn("Coin")). Game time (pause and timeScale count). Returns a function that stops it; stops when this object is destroyed.

field — field​

The kinds of field a script declares with export let speed = 2.

MemberTypeDescription
object()fieldA field where each object picks another object in the Inspector: export let target = field.object(). target is that object, or null.
image()fieldA picture picked from the project files: export let icon = field.image(). icon is the file, { id, name, kind } (or null); entity.setUIImage(icon) shows it.
sound()fieldA sound picked from the project files: export let hit = field.sound(). audio.play(hit) plays it; hit.name is its file name.
prefab()fieldA prefab picked from the project: export let drop = field.prefab(). game.spawn(drop) creates it; drop.name is its name.
component(type)fieldAn object that has this component, picked in the Inspector, read as its component: export let lamp = field.component('light'), then lamp.intensity = 2.
behavior(type)fieldAn object that has this behavior, read as the behavior: export let hp = field.behavior('health'), then hp.damage(1).
script(name)fieldAn object that has this code script, read as the script: export let enemy = field.script('Enemy'), then enemy.hp = 5.
choice(...words)fieldA dropdown of fixed words: export let kind = field.choice('Sword', 'Potion'). kind is the chosen word; the first is the default.
color(default?)fieldA colour picker: export let tint = field.color('#ff8800'). tint is '#rrggbb'.
list(of)fieldA list the Inspector edits (add, remove, reorder). field.list(Item) is a list of your own class Item; field.list(field.image()) or field.list(0) work too. The variable is an array.
data(table)fieldA row picked from a data table made in Files: export let loot = field.data("Item"). loot is the row (or null).

collision — collision​

Second argument of onCollision / onCollisionStay / onCollisionEnd (third for game scripts): what was hit, where and how hard (like Unity's Collision).

MemberTypeDescription
otherentityThe object it hit.
selfentityThe object this collision is reported to.
isTriggerbooleanOne of them is a trigger: they overlap, no contacts.
contactsContactPoint[]Every contact: { point, normal, separation, impulse }. World space; normals point out of other.
contactCountnumberHow many contacts.
point{x,y,z}Where they touched (first contact).
normal{x,y,z}Surface direction at the hit, out of other toward this object (y = 1: landed on top of it).
impulse{x,y,z}Total impulse that pushed this object away (N·s); its length is how hard they hit.
relativeVelocity{x,y,z}Velocity of other relative to this object as they met (m/s).
speednumberImpact speed (length of relativeVelocity), e.g. for damage or a sound volume.
colliderRapier ColliderThe other object's collider that touched.
thisColliderRapier ColliderThis object's collider that touched.
rigidbodyRapier RigidBody|nullThe other object's physics body.
flipped()collisionThe same collision from the other object's side.

particleSystem — entity.particleSystem​

An object's Particle System, like Unity's ParticleSystem.

MemberTypeDescription
mainmoduleThe main module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
emissionmoduleThe emission module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
shapemoduleThe shape module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
velocityOverLifetimemoduleThe velocityOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
limitVelocityOverLifetimemoduleThe limitVelocityOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
inheritVelocitymoduleThe inheritVelocity module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
lifetimeByEmitterSpeedmoduleThe lifetimeByEmitterSpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
forceOverLifetimemoduleThe forceOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
colorOverLifetimemoduleThe colorOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
colorBySpeedmoduleThe colorBySpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
sizeOverLifetimemoduleThe sizeOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
sizeBySpeedmoduleThe sizeBySpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
rotationOverLifetimemoduleThe rotationOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
rotationBySpeedmoduleThe rotationBySpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
externalForcesmoduleThe externalForces module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
noisemoduleThe noise module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
collisionmoduleThe collision module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
triggersmoduleThe triggers module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
subEmittersmoduleThe subEmitters module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
textureSheetAnimationmoduleThe textureSheetAnimation module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
lightsmoduleThe lights module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
trailsmoduleThe trails module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
customDatamoduleThe customData module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
renderermoduleThe renderer module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }.
isPlayingbooleanPlaying (emitting, or particles still flying), not paused.
isEmittingbooleanMaking new particles.
isPausedbooleanPaused.
isStoppedbooleanStopped and every particle gone.
particleCountnumberParticles alive.
timenumberSeconds into the current cycle (settable).
play(withChildren = true)voidPlay (or carry on after pause).
pause(withChildren = true)voidFreeze in place.
stop(withChildren = true, stopBehavior = "stopEmitting")voidStop emitting; "stopEmittingAndClear" also removes the particles.
clear(withChildren = true)voidRemove every particle.
isAlive(withChildren = true)booleanEmitting or particles still alive.
emit(count, params?)voidEmit now. params override start values: { position, velocity, startSize, startColor, startLifetime, rotation, … }.
simulate(t, withChildren = true, restart = true, fixedTimeStep = true)voidFast-forward t seconds (leaves it paused).
getParticles()Particle[]Every live particle: position, velocity, remainingLifetime, startSize, startColor, rotation, … (a copy).
setParticles(particles, size?)voidWrite particles back (change getParticles() results); extra ones are removed.
triggerSubEmitter(index, particles?)voidFire a sub emitter from every particle, or the given ones.
getCustomParticleData(stream = 1){x,y,z,w}[]Custom Data stream 1 or 2 per particle (what a renderer shader gets as vCustom1 / vCustom2).
setCustomParticleData(data, stream = 1)voidSet Custom Data per particle (getParticles() order); keep the stream Disabled in the module so it is not worked out again.

trailRenderer — entity.trailRenderer​

An object's Trail Renderer, like Unity's TrailRenderer.

MemberTypeDescription
timenumberSeconds a point lasts.
minVertexDistancenumberMeters moved before a new point is dropped.
emittingbooleanOff: no new points; the trail left so far still fades.
autodestructbooleanDestroy the object once its trail has faded out.
width{ scale, keys }Width along the trail: scale is the width, keys shape it from the object (t 0) to the tail (t 1).
color{ colors, alphas }Color gradient along the trail, object to tail.
alignment"view" | "transformZ"Face the camera, or the object's Z axis.
textureMode"stretch" | "tile" | "distributePerSegment" | "repeatPerSegment"How the texture runs along the trail.
blending"alpha" | "additive"Additive glows.
positionCountnumberPoints in the trail now.
getPosition(index){x,y,z}|nullA point, oldest first (world space).
getPositions(){x,y,z}[]Every point, oldest first.
addPosition(position)voidAdd a point by hand.
clear()voidRemove every point (after a teleport, so no streak joins the two places).

lineRenderer — entity.lineRenderer​

An object's Line Renderer, like Unity's LineRenderer.

MemberTypeDescription
positionCountnumberPoints on the line; setting it adds copies of the last point or drops points from the end.
loopbooleanJoin the last point back to the first.
useWorldSpacebooleanPoints are world positions (true) or in the object's own space.
width{ scale, keys }Width along the line: scale is the width, keys shape it from the first point (t 0) to the last (t 1).
color{ colors, alphas }Color gradient along the line, first point to last.
alignment"view" | "transformZ"Face the camera, or the object's Z axis.
textureMode"stretch" | "tile" | "distributePerSegment" | "repeatPerSegment"How the texture runs along the line.
blending"alpha" | "additive"Additive glows.
getPosition(index){x,y,z}|nullA point.
setPosition(index, position)voidMove a point, e.g. a laser's end to where its ray hit.
getPositions(){x,y,z}[]Every point.
setPositions(positions)voidReplace every point.

Globals​

NameTypeDescription
entityentityThe entity this script is attached to.
gamegameThe game: find/spawn entities, variables, scenes...
inputinputJoystick, buttons, taps and swipes.
audioaudioPlay sounds.
fieldfieldsThe kinds of field for export let: field.object(), field.image(), field.sound(), field.prefab(), field.choice(…), field.color(), field.list(…), field.data(table), field.component(type), field.behavior(type), field.script(name).
varsobjectVariables storage for this script.
THREEthree.jsThe three.js library, e.g. game.three.scene.add(new THREE.Mesh(geometry, material)). Same as import * as THREE from "three".
RAPIERrapier3dThe physics library (Rapier), e.g. RAPIER.JointData.fixed(…) with game.rapier.world. Same as import * as RAPIER from "rapier".

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.
export let speed = 5; // meters per second, set per object in the Inspector

function update(dt) {
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).
export let jumpStrength = 7;

function update(dt) {
if (input.wasPressed('jump') && entity.isOnGround()) {
const v = entity.getVelocity();
entity.setVelocity(v.x, jumpStrength, v.z);
}
}

Tap to move​

Tap the ground and walk there, around walls.

// Tap (or click) the ground: walk there, going around walls.
export let speed = 4;

function update(dt) {
if (input.tapped) {
const p = game.touchWorld();
entity.moveTo(p.x, p.z, speed);
}
}

Spin​

Rotate constantly around the up axis.

// Spin around the Y axis.
export let speed = 90; // degrees per second

function update(dt) {
entity.rotate(0, speed * dt, 0);
}

Follow the player​

Chase the entity named "Player" and stop when close.

// Chase the Player.
export let speed = 2;

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, speed * dt);
}
}

Patrol between two points​

Walk back and forth between two objects you pick in the Inspector (each enemy its own).

// Walk back and forth between two objects picked in the Inspector.
// Put this script on any number of enemies and give each its own Point A and Point B
// (empty objects make good markers). The fields below show up in the Inspector.
export let speed = 2; // meters per second
export let pointA = field.object(); // pick an object in the Inspector
export let pointB = field.object();
export let pause = 0.5; // seconds to wait at each end

let goingToB = true;
let waitLeft = 0;

function update(dt) {
const target = goingToB ? pointB : pointA;
if (!target) return; // not picked yet
if (waitLeft > 0) { waitLeft -= dt; return; }
const me = entity.getWorldPosition();
const p = target.getWorldPosition();
entity.lookAt(p.x, me.y, p.z); // face it, staying upright
entity.moveToward(p.x, me.y, p.z, speed * dt);
if (Math.hypot(p.x - me.x, p.z - me.z) < 0.2) {
goingToB = !goingToB; // turn around
waitLeft = pause;
}
}

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'));
}

Web request (global)​

// Global script: ask a web server for data and send a score.
// Only https:// works. A game played from the gallery may only contact the domains you list in
// Project settings → Web requests → Allowed domains.
async function loadScores() {
const r = await game.http.get('https://example.com/scores.json');
if (!r.ok) { game.log('No scores: ' + r.error); return; } // never throws: a failure is ok = false
game.setVar('TopName', r.json.list[0].name); // r.json is the reply read as JSON
}

async function sendScore() {
// An object is sent as JSON. Never put a secret key in a game: call your own server instead.
const r = await game.http.post('https://example.com/score', { name: 'Ann', score: game.getVar('Score') });
if (!r.ok) game.log('Score not sent: ' + r.error);
}

loadScores();
game.on('died', sendScore);

Multiplayer room (global)​

// Global script: make a room, show its code, and share each player's position.
// One player runs create(); the others run join(code) with the code they were given.
// The room only relays messages (it never runs your game): everyone moves their own object and tells the others.
async function start() {
const r = await game.net.create({ name: 'Player', max: 4 });
if (!r.ok) { game.log('No room: ' + r.error); return; } // never throws: "notfound", "full", "busy" or "offline"
game.setVar('RoomCode', r.code); // show it in a Text, friends type it to join
}

// A friend: await game.net.join(game.getVar('CodeTyped'), { name: 'Bo' });

game.on('netPlayerJoined', (e) => game.log(e.player.name + ' joined'));
game.on('netPlayerLeft', (e) => game.log(e.player.name + ' left'));

// Receive: move the matching puppet (an object named after the player) to where they say they are.
game.on('netMessage', (m) => {
if (m.name !== 'pos') return;
const puppet = game.find(m.from.name);
if (puppet) puppet.setPosition(m.data.x, m.data.y, m.data.z);
});

// Send my position about ten times a second (at most 30 messages a second are allowed).
let timer = 0;
function update(dt) {
timer += dt;
if (timer < 0.1 || game.net.state !== 'online') return;
timer = 0;
const me = game.find('Player');
if (me) game.net.send('pos', { x: me.position.x, y: me.position.y, z: me.position.z });
}

start();

Multiplayer players (global)​

// Global script: every player gets a car that all the others see. Needs a prefab called "Car".
// game.net.spawn makes it for everyone; you drive yours, the others' cars glide along by themselves.
let mine = null;

game.on('netJoined', () => {
mine = game.net.spawn('Car', { x: game.net.me.id * 3, y: 1, z: 0 });
});

function update(dt) {
if (!mine || mine.destroyed) return;
// Only read input for the car that is yours. Cars of other players have isMine === false.
if (mine.isMine) mine.translate(input.axis.x * 5 * dt, 0, -input.axis.y * 5 * dt);
}

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);
}

Get in and out of a vehicle​

Put on the Player. Press the "use" button next to a boat or car (tag #vehicle) to get in or out. Seating and the camera are automatic; steering is yours.

// Put this on the Player. Give the vehicle the tag "vehicle" and a Car or Boat behavior, and add
// a control button called "use" in Scene → Controls.
function update(dt) {
const vehicle = entity.vehicle;

if (input.wasPressed('use')) {
if (vehicle) {
entity.exitVehicle(); // put down beside it, walking again, camera back on you
} else {
// Get in: the nearest vehicle within 3 meters.
let nearest = null;
for (const v of game.select('#vehicle')) {
if (entity.distanceTo(v) < 3 && (!nearest || entity.distanceTo(v) < entity.distanceTo(nearest))) nearest = v;
}
if (nearest) entity.enterVehicle(nearest); // sits in the seat, camera follows
}
return;
}

// Entering does not steer: pass the joystick to whoever you are driving.
if (vehicle) {
if (vehicle.behavior('car')) vehicle.driveCar(input.axis.x, Math.max(input.axis.y, 0), Math.max(-input.axis.y, 0));
else vehicle.setMoveInput(input.axis.x, input.axis.y);
} else {
entity.setMoveInput(input.axis.x, input.axis.y);
}
}

Drive a car or walk with the joystick​

Put on a Car, Boat or Platformer object. The behavior never reads the joystick: you pass it in.

// Put this on an object with a Car (or Boat, or Platformer) behavior. The behavior does
// nothing until you tell it what to do; read the joystick and pass it in.
function update(dt) {
const x = input.axis.x; // left / right
const y = input.axis.y; // up / down

// Car: steer, gas, brake
entity.driveCar(x, Math.max(y, 0), Math.max(-y, 0));

// Boat or Platformer / Top-down instead:
// entity.setMoveInput(x, y);
// if (input.wasPressed('jump')) entity.simulateControl('jump');
}