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. | ✔ | |
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()).
| 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. |
layer | string | The 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. |
persist | boolean | True: 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. |
destroyed | boolean | True once the entity has been destroyed. |
drawsLayer(layer) | boolean | A camera: true while it draws objects on this layer (its Draw <layer> switch). False on an object without a camera. |
setDrawLayer(layer, draw) | void | A 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 |
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. |
setSpin(x, y, z) | void | Set how fast it spins, in degrees per second around the world X, Y and Z axes. |
applyImpulse(x, y, z) | void | Instant push, e.g. a jump: applyImpulse(0, 5, 0) |
breakJoint(index?: number) | void | Cut 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) | void | Drive 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) | void | Turn the joint motor off: it turns or slides freely again. |
getJointAngle(index?: number) | number | Hinge: angle in degrees from where it started; slider: metres moved. |
getJointSpeed(index?: number) | number | Hinge / wheel: turning speed in degrees per second; slider: metres per second. |
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. |
setUniform(name, value) | boolean | Set 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) | boolean | Show 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) | void | Set the text of a Text component. |
getText() | string | Get the text of a Text component. |
getUIValue() | number | Slider (or bar) value (UI component). |
setUIValue(value) | void | Set the slider value, e.g. health. |
getUIMax() | number | Slider maximum. |
setUIMax(max) | void | Set the slider maximum. |
getUIMin() | number | Slider minimum. |
setUIMin(min) | void | Set the slider minimum. |
setUIImage(assetName) | void | Change the image of a UI element. |
setUIFont(assetName) | void | Change the font of a UI element's text ('' = the default font). |
setUIColors({ background, text, fill }) | void | Change UI colors, e.g. { background: "#ff0000" }. |
setUIInteractable(on) | void | Grey a button or slider out, or turn it back on (Interactable). |
selectUI() | void | Choose this button or slider for the controller and arrow keys, e.g. when a menu opens (Unity Select()). |
isUISelected() | boolean | Is this button or slider the one the controller or arrow keys have chosen? |
focusUI() | void | Input Field: start typing in it. Read and set what is typed with getText() / setText(). |
isUIFocused() | boolean | Input Field: is the player typing in it right now? |
isToggleOn() | boolean | Toggle: is it on (ticked)? |
setToggleOn(on: boolean) | void | Toggle: 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[]) | void | Dropdown: replace its options (a resolution list, save slots). |
addUIOption(text: string) | void | Dropdown: add an option at the end. |
htmlRoot | ShadowRoot | null | HTML element: the shadow root its markup is drawn in, e.g. entity.htmlRoot.querySelector("#name").value or .addEventListener("input", …). |
setHTML(html: string) | void | HTML 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) | void | Move a UI element to this anchored position (canvas px). Leave an axis out (undefined) to keep it. |
isUI() | boolean | Is 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) | void | Put 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) | void | Set a UI element's width and height. Leave one out (undefined) to keep it. |
setUIAnchors(minX, minY, maxX, maxY) | void | Anchors as fractions of the parent (0,0 is bottom-left). Same corner: fixed size; apart: stretch. |
setUIPivot(x, y) | void | The point of the element that its position, rotation and scale refer to, as a fraction of its own box. |
moveUITo(target, offsetX, offsetY) | void | Put 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() | void | Re-apply the UI styles after writing component data directly. |
isPressed() | boolean | True while this UI button is held down. |
playAnimation(name: string, loop = true) | void | Play 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. |
animator | Animator|null | The 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() | void | Stop the playing model animation. |
isMine | boolean | In 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. |
owner | NetPlayer|null | In a multiplayer room: the player who drives the object, or null. |
ragdoll(on = true, opts?) | void | Make 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) | void | Powered 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) | void | Push the limp character's bones whose name contains bone (e.g. "arm", "head"), an impulse shared out by their mass. |
getAnimation() | string | Name of the playing clip (empty if none). |
isAnimationBusy() | boolean | True 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) | boolean | True if the model (or sprite) has this clip. |
setAnimationSpeed(speed: number) | void | 1 = normal, 0.5 = half, 2 = double. |
setSpriteFrame(frame: number) | void | Sprite: show one frame (0 = the first) and stop its animation. playAnimation() plays again. |
setSpritePart(layer: string, label: string) | void | Sprite drawn in layers: show another picture on a layer, e.g. setSpritePart("Face", "Angry") (Unity's Sprite Resolver). |
getSpritePart(layer: string) | string | Sprite drawn in layers: the label of the picture a layer shows. |
getSpriteFrame() | number | Sprite: the frame being shown (0 = the first). |
getSpriteFrameCount() | number | Sprite: how many frames it has. |
setTile(x: number, y: number, tile: number) | void | Tilemap: 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) | number | Tilemap: the tile in a cell, or -1 when it is empty. |
removeTile(x: number, y: number) | void | Tilemap: erase a cell. |
cellAt(worldX: number, worldY: number) | { x, y } | Tilemap: the cell at a world position. |
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. |
morphTargets | string[] | 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?) | boolean | Model: 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?) | boolean | Post-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) | number | Model: how far a morph target is applied, 0 to 1. |
video | {play,pause,restart,playing}|null | The 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?) | void | Carry 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() | void | Let go: back to the top level where it is now. |
particleSystem | ParticleSystem|null | The 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. |
lineRenderer | LineRenderer|null | The 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. |
trailRenderer | TrailRenderer|null | The 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) | void | Shoot particles at once from the Particle System, e.g. emitParticles(30) on a hit. |
startParticles() | void | Play the Particle System (bursts at time 0 go out). Safe to call every frame: already playing means nothing changes. |
restartParticles() | void | Play the Particle System from the beginning even if it is already playing. |
stopParticles(clear?: boolean) | void | Stop making new particles; the ones out finish their life, or go at once with stopParticles(true). |
setParticleRate(rate: number) | void | Emission rate over time (particles per second). |
isEmittingParticles() | boolean | True while the Particle System makes new particles. |
getParticleCount() | number | Particles currently alive. |
makeLiveCamera() | void | Virtual 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?) | boolean | Can 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)) … |
director | TimelineAPI | null | Playable 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(). |
isLiveCamera | boolean | Virtual Camera: true while it is the one moving the main camera. |
resetCloth() | void | Cloth: every point back on the plane, hanging still. Its settings are component("cloth"), e.g. component("cloth").windScale = 2. |
playSound() | void | Play this entity's Audio component. |
stopSound(fadeOut = 0) | void | Stop the sound of its Sound component, fading out over fadeOut seconds. |
getComponent(type) | object|null | A 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|null | A 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|null | Add 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) | boolean | Remove a component and rebuild. |
rebuild() | void | Rebuild the object from its components (3D content, body, text, UI, particles, behaviors), keeping where it is and its variables. |
hasComponent(type) | boolean | Does it have this component or behavior? e.g. other.hasComponent("health") |
getScript(name) | script|null | A 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|null | A 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|null | Add a behavior and start it now, e.g. addBehavior("bullet", { speed: 20 }) |
removeBehavior(type) | boolean | Stop and remove a behavior. |
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) |
damage(amount, from?) | void | Health behavior: lose health; from = what hit it (for Knockback). Fires On hurt / On death. |
heal(amount) | void | Health behavior: get health back, up to Max health. Current health: getVar("health"). |
moveTo(x, z, speed?, options?) | void | Walk 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() | void | Cancel moveTo(). |
movingTo | boolean | A moveTo() is under way. |
inWater | boolean | In a Water object (a physics body: any part of it). |
enterVehicle(vehicle) | void | Get 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() | void | Get out, beside the vehicle (on land if possible). |
driveCar(steer, gas, brake) | void | Drive 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) | void | Move 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) | void | Press 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. |
vehicle | entity|null | The vehicle it is riding, or null. |
hasDriver | boolean | A boat or car someone got into (Enter vehicle). |
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? |
loadingProgress | number | On 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. |
isLoading | boolean | A loading screen is up and the game has not moved on yet. |
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") |
query(selector) | EntitySet | Pick 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|null | First live entity matching a selector: game.first("#enemy") |
getAllEntities() | entity[] | Every live entity. |
spawn(name, position?, rotation?, parent?) | entity|null | Create 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|null | Make 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) | void | Destroy an entity. |
pick(screenX, screenY) | entity|null | Entity 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) | void | Fire "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) | boolean | True 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}|null | Physics 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) | boolean | Are two entities touching? |
touchInfo(a, b) | CollisionInfo | null | Current contact of two touching entities (point, normal, speed, impulse), or null |
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. |
saveGame(slot?) | boolean | Save 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?) | boolean | Bring 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?) | boolean | Is there a saved game in the slot? Show a Continue button when there is. |
deleteSaveGame(slot?) | void | Remove a saved game from the device. |
table(name) | table | A data table made in Files: game.table("Item").get("Sword"), .all(), .where(r => r.damage > 5), .ids(), .has(name), .length. |
language | string | Current 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) | string | A 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. |
navmesh | NavMesh | The 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. |
steam | SteamAPI | Steam 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"). |
services | ServicesAPI | Achievements, 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", …). |
http | HttpAPI | Web 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", …). |
net | NetAPI | Rooms 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) | Timeline | A 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) | RenderTexture | A 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|null | The 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?) | void | Play 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?) | void | Shake 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 | null | The 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?) | boolean | Stick 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) | void | Vibrate 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() | void | Close 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) | unsubscribe | Listen: "sceneStart", "collisionStart", "entityCreated", "waterEnter", "seen", ... |
after(seconds, fn, owner?) | cancel | Run 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?) | stop | Run 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. |
events | messages | Messages 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) | void | Show a message on screen and in the Play console (debugging). |
consoleLog(...values) | void | Write a line to the Play console only, nothing on screen. console.log() in a script does the same. |
input — input
Touch controls and keyboard.
| Member | Type | Description |
|---|---|---|
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. |
gamepad | boolean | A gamepad has been used. Its buttons work as keys: "PadA", "PadB", "PadX", "PadY", "PadLB", "PadRB", "PadLT", "PadRT", "PadStart". |
device | string | What the player used last: "gamepad", "keyboard" (keys or mouse) or "touch". Show button prompts for it. |
deviceChanged | boolean | True for the one frame the device changes: update button prompts then. |
padStyle | string | Whose button names gamepad prompts show: "xbox", "playstation" (✕ ○ □ △), "switch" or "deck". From the gamepad in use. |
setPadStyle(style) | void | Force a gamepad prompt style, or "auto" to follow the gamepad again. |
padStyleChanged | boolean | True for the one frame the prompt style changes. |
prompt(action, device?) | string | The 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. |
rebinding | string|null | The action waiting for a key, or null. |
rebound | string|null | The action rebound this frame, or null. |
cancelRebind() | void | Stop 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?}) | void | Give an action these keys / gamepad buttons (kept on this device). |
resetBindings(action?) | void | Back to the game's own controls: one action, or all. |
isDown(name) | boolean | Button, key or gamepad button held, e.g. input.isDown("jump"), input.isDown("Space"), input.isDown("PadA") |
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, group, pitch, fadeIn}?) | SoundHandle | Play 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?) | void | Stop sounds with a tag (or all), fading out over fadeOut seconds. |
isPlaying(tag?) | boolean | A sound with that tag (or any) is playing. |
playMusic(nameOrId, {volume, fade, group, loop, sync}?) | void | Play 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) | void | Fade the music out. |
setMusicLayer(layer, volume, fade = 1) | void | Adaptive music: fade a layer of the music (a beat made with layers) to a volume, 0 … 1. It stays so until changed. |
getMusicLayer(layer) | number | The volume of a music layer (1 unless changed). |
musicBeat | number | Beats 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). |
musicBar | number | Bars since the music started, -1 when none. |
musicTime | number | Seconds into the music playing. |
musicBpm | number | The music’s tempo (0 when unknown). |
music | string | Name of the music playing, or "". |
setGroupVolume(group, 0..1, fade?) | void | Volume of a mixer group (Project settings → Audio mixer), smoothly over fade seconds. "Master" is the master volume. |
getGroupVolume(group) | number | Volume of a mixer group. |
setGroupMuted(group, muted) | void | Silence a mixer group, or bring it back. |
setGroupLowpass(group, hz, fade?) | void | Muffle a mixer group (e.g. 600 under water); 0 turns the filter off. |
setMasterVolume(0..1) | void | Global volume. |
getMasterVolume() | number | Global volume. |
pauseAll() | void | Pause every sound (a pause menu). |
resumeAll() | void | Carry on where they were. |
paused | boolean | Sounds are paused. |
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.). |
wait(seconds) | Promise | Carry 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) | cancel | Run 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) | stop | Run 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.
| Member | Type | Description |
|---|---|---|
object() | field | A field where each object picks another object in the Inspector: export let target = field.object(). target is that object, or null. |
image() | field | A 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() | field | A sound picked from the project files: export let hit = field.sound(). audio.play(hit) plays it; hit.name is its file name. |
prefab() | field | A prefab picked from the project: export let drop = field.prefab(). game.spawn(drop) creates it; drop.name is its name. |
component(type) | field | An 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) | field | An object that has this behavior, read as the behavior: export let hp = field.behavior('health'), then hp.damage(1). |
script(name) | field | An object that has this code script, read as the script: export let enemy = field.script('Enemy'), then enemy.hp = 5. |
choice(...words) | field | A dropdown of fixed words: export let kind = field.choice('Sword', 'Potion'). kind is the chosen word; the first is the default. |
color(default?) | field | A colour picker: export let tint = field.color('#ff8800'). tint is '#rrggbb'. |
list(of) | field | A 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) | field | A 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).
| Member | Type | Description |
|---|---|---|
other | entity | The object it hit. |
self | entity | The object this collision is reported to. |
isTrigger | boolean | One of them is a trigger: they overlap, no contacts. |
contacts | ContactPoint[] | Every contact: { point, normal, separation, impulse }. World space; normals point out of other. |
contactCount | number | How 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). |
speed | number | Impact speed (length of relativeVelocity), e.g. for damage or a sound volume. |
collider | Rapier Collider | The other object's collider that touched. |
thisCollider | Rapier Collider | This object's collider that touched. |
rigidbody | Rapier RigidBody|null | The other object's physics body. |
flipped() | collision | The same collision from the other object's side. |
particleSystem — entity.particleSystem
An object's Particle System, like Unity's ParticleSystem.
| Member | Type | Description |
|---|---|---|
main | module | The main module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
emission | module | The emission module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
shape | module | The shape module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
velocityOverLifetime | module | The velocityOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
limitVelocityOverLifetime | module | The limitVelocityOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
inheritVelocity | module | The inheritVelocity module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
lifetimeByEmitterSpeed | module | The lifetimeByEmitterSpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
forceOverLifetime | module | The forceOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
colorOverLifetime | module | The colorOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
colorBySpeed | module | The colorBySpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
sizeOverLifetime | module | The sizeOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
sizeBySpeed | module | The sizeBySpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
rotationOverLifetime | module | The rotationOverLifetime module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
rotationBySpeed | module | The rotationBySpeed module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
externalForces | module | The externalForces module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
noise | module | The noise module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
collision | module | The collision module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
triggers | module | The triggers module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
subEmitters | module | The subEmitters module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
textureSheetAnimation | module | The textureSheetAnimation module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
lights | module | The lights module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
trails | module | The trails module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
customData | module | The customData module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
renderer | module | The renderer module, live: change any setting (the same names as the Inspector). Numbers can be a constant or { mode: "twoConstants", constantMin, constantMax, … }. |
isPlaying | boolean | Playing (emitting, or particles still flying), not paused. |
isEmitting | boolean | Making new particles. |
isPaused | boolean | Paused. |
isStopped | boolean | Stopped and every particle gone. |
particleCount | number | Particles alive. |
time | number | Seconds into the current cycle (settable). |
play(withChildren = true) | void | Play (or carry on after pause). |
pause(withChildren = true) | void | Freeze in place. |
stop(withChildren = true, stopBehavior = "stopEmitting") | void | Stop emitting; "stopEmittingAndClear" also removes the particles. |
clear(withChildren = true) | void | Remove every particle. |
isAlive(withChildren = true) | boolean | Emitting or particles still alive. |
emit(count, params?) | void | Emit now. params override start values: { position, velocity, startSize, startColor, startLifetime, rotation, … }. |
simulate(t, withChildren = true, restart = true, fixedTimeStep = true) | void | Fast-forward t seconds (leaves it paused). |
getParticles() | Particle[] | Every live particle: position, velocity, remainingLifetime, startSize, startColor, rotation, … (a copy). |
setParticles(particles, size?) | void | Write particles back (change getParticles() results); extra ones are removed. |
triggerSubEmitter(index, particles?) | void | Fire 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) | void | Set 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.
| Member | Type | Description |
|---|---|---|
time | number | Seconds a point lasts. |
minVertexDistance | number | Meters moved before a new point is dropped. |
emitting | boolean | Off: no new points; the trail left so far still fades. |
autodestruct | boolean | Destroy 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. |
positionCount | number | Points in the trail now. |
getPosition(index) | {x,y,z}|null | A point, oldest first (world space). |
getPositions() | {x,y,z}[] | Every point, oldest first. |
addPosition(position) | void | Add a point by hand. |
clear() | void | Remove every point (after a teleport, so no streak joins the two places). |
lineRenderer — entity.lineRenderer
An object's Line Renderer, like Unity's LineRenderer.
| Member | Type | Description |
|---|---|---|
positionCount | number | Points on the line; setting it adds copies of the last point or drops points from the end. |
loop | boolean | Join the last point back to the first. |
useWorldSpace | boolean | Points 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}|null | A point. |
setPosition(index, position) | void | Move a point, e.g. a laser's end to where its ray hit. |
getPositions() | {x,y,z}[] | Every point. |
setPositions(positions) | void | Replace every point. |
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. |
field | fields | The 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). |
vars | object | Variables storage for this script. |
THREE | three.js | The three.js library, e.g. game.three.scene.add(new THREE.Mesh(geometry, material)). Same as import * as THREE from "three". |
RAPIER | rapier3d | The 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:
| 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.
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');
}