VYOM SCRIPTING DOCS
← Home

VYOM Engine
Scripting Docs

Make 2D and 3D games with plain JavaScript. Every command below is explained in simple words, with how to write it, what goes inside the brackets, and an example you can copy.

490COMMANDS
367FOR 2D GAMES
260FOR 3D GAMES
22CATEGORIES

Getting started

  1. Create a project (Project Manager → New Project → choose a template).
  2. In the FileSystem dock double-click a .js file (or Scene dock → Attach script on a node) to open it in the script editor.
  3. Press F5 (Play) or F6 (Play scene). print() output and errors appear in the Output panel.

A 2D script has the same shape as a Game Lab program:

var ball;
function start() {
  ball = createSprite(200, 200, 30, 30);
  ball.shapeColor = "red";
  ball.setSpeed(4, 45);
  createEdgeSprites();
}
function update() {
  ball.bounceOff(edges);
}
function draw() {
  background("white");
  drawSprites();
}

How scripts run

2D tutorial

Coin collector

Create a project from the Empty 2D template, add a new script (FileSystem → New Script, "2D template"), attach it to the root node and replace its contents:

var player, coins, score;

// start() runs once when the game begins
function start() {
  score = 0;
  createEdgeSprites();
  player = createSprite(200, 350, 40, 40);
  player.shapeColor = "blue";
  coins = createGroup();
  for (var i = 0; i < 8; i++) {
    var c = createSprite(randomNumber(20, 380), randomNumber(20, 250), 20, 20);
    c.shapeColor = "gold";
    coins.add(c);
  }
}

// update() runs every frame: handle input and game rules
function update() {
  if (keyDown("LEFT_ARROW")) { player.x -= 5; }
  if (keyDown("RIGHT_ARROW")) { player.x += 5; }
  player.collide(edges);
  player.overlap(coins, function (p, coin) {
    coin.destroy();
    score++;
  });
}

// draw() runs after update(): draw the picture
function draw() {
  background("white");
  drawSprites();
  fill("black");
  textSize(18);
  text("Score: " + score, 10, 24);
}

Run it with F5: move the blue square with the arrow keys and touch the gold squares. createGroup() holds the coins, overlap() calls your function for each coin touched, collide(edges) keeps the player inside the screen.

Gravity and jumping

var hero, ground;

function start() {
  World.gravity = 0.8;
  hero = createSprite(100, 100, 30, 40);
  hero.shapeColor = "red";
  ground = createSprite(200, 390, 400, 20);
  ground.immovable = true;
}

function update() {
  hero.velocityX = 0;
  if (keyDown("LEFT_ARROW")) { hero.velocityX = -4; }
  if (keyDown("RIGHT_ARROW")) { hero.velocityX = 4; }
  hero.collide(ground);
  // only jump while standing on the ground
  if (keyWentDown("SPACE") && hero.isTouching(ground)) { hero.velocityY = -14; }
}

function draw() {
  background("skyblue");
  drawSprites();
}

World.gravity pulls every sprite that is not immovable down. The ground is immovable, collide() stops the hero on it and isTouching() tells us when a jump is allowed.

Animations

Import a sprite sheet (drag the PNG into the FileSystem dock), open it in Asset view, press Animation editor, select the frames and save idle and walk. Then:

var hero;
function start() {
  hero = createSprite(200, 200, 32, 32);
  // "walk" and "idle" were made in Tools > Sprite & Animation Maker and saved in animations/
  hero.setAnimation("idle");
}
function update() {
  if (keyDown("RIGHT_ARROW")) {
    hero.changeAnimation("walk");
    hero.x += 3;
  } else {
    hero.changeAnimation("idle");
  }
}
function draw() {
  background("white");
  drawSprites();
}

Sprite & Animation Maker (draw, clean up and animate pictures)

Open it from Tools > Sprite & Animation Maker, the Sprite Maker button in the Asset view, or right-click a picture in the FileSystem dock > Edit in Sprite Maker.

Why touching used to trigger too early: a big picture with empty (transparent) space around the character has a big box. Trim it in the maker, or in code call sprite.setCollider("auto"). Scene nodes (getNode("Player").isTouching(...)) already use only the visible pixels of Sprite2D / AnimatedSprite2D pictures.

var hero, coin;
function start() {
  hero = createSprite(100, 200);
  hero.setAnimation("hero");     // made in the Sprite & Animation Maker
  hero.setCollider("auto");      // the touching box hugs the visible art, not the whole picture
  coin = createSprite(300, 200);
  coin.setAnimation("coin");
}
function update() {
  if (hero.isTouching(coin)) { coin.remove(); }
}
function draw() {
  background("white");
  drawSprites();
}

Exported variables (numbers, text and true/false with a literal value; the optional [min,max,step] after @export gives a slider range in the Inspector):

var speed = 4;      // @export [1,12,1]
var label = "Hero"; // @export
var hard = false;   // @export

function start() {
  print(label + " runs at speed " + speed + (hard ? " (hard mode)" : ""));
}

3D tutorial

Spinning object

Create a project from Empty 3D, add a MeshInstance3D (give it a mesh in the Inspector), attach a script:

// Attach this script to a Node3D (for example a MeshInstance3D) in a 3D scene.
function update(dt) {
  rotate3D(0, 45, 0);   // 45 degrees per second around the Y axis
}

Walking player

// Attach this script to a CharacterBody3D that has a CollisionShape3D.
var speed = 5;   // @export [1,20,0.5]
var jump = 6;    // @export [1,15,0.5]

function update(dt) {
  var move = vec3(0, 0, 0);
  if (keyDown("w")) { move.z = -1; }
  if (keyDown("s")) { move.z = 1; }
  if (keyDown("a")) { move.x = -1; }
  if (keyDown("d")) { move.x = 1; }
  velocity3D.x = move.x * speed;
  velocity3D.z = move.z * speed;

  if (isOnFloor3D()) {
    if (keyWentDown("space")) { velocity3D.y = jump; }
  } else {
    velocity3D.y -= gravity3D * dt;   // gravity is not automatic
  }
  moveAndSlide3D();
}

velocity3D is the CharacterBody3D's velocity in metres per second, moveAndSlide3D() moves it and slides along walls, isOnFloor3D() is true while standing. Gravity is not applied automatically so scripts stay in control. The 3D First-person and Third-person templates contain complete versions.

Raycasts

// Look straight down from the player: how far is the ground?
function update(dt) {
  var hit = raycast3D(getPosition3D(), vec3(0, -1, 0), 20);
  if (hit && World3D.frameCount % 60 === 0) {
    print("Ground is " + hit.distance.toFixed(2) + " m below, it is " + hit.collider.name);
  }
}

Making a Granny-style game

The 2D helpers you know (isTouching, distanceTo, moveTowards, hide, show, x/y/z, mouse checks) work on 3D nodes too, and there is a small kit for horror / stealth games: chase, patrol, wander, canSee, faceTowards, isLookingAt (crosshair), giveItem / takeItem / hasItem, setGlobal / getGlobal (shared between scripts) and showMessage. Start from the 3D First-person template: add a Granny (CharacterBody3D + CollisionShape3D + mesh), a Key, and a Door (StaticBody3D + CollisionShape3D + mesh). Everything that should be pickable or blocking needs a collision shape.

Player script:

// Attach to the Player (a CharacterBody3D with a Camera3D child), like the First-person template.
var yaw = 0, pitch = 0, speed = 4;
var cam, key, door, granny;

function start() {
  cam = getNode3D("Camera3D");
  key = getNode3D("Key");
  door = getNode3D("Door");
  granny = getNode3D("Granny");
  captureMouse(true);
  showMessage("Find the key and get out...", 5);
}

function update() {
  yaw -= mouseDeltaX() * 0.12;
  pitch = constrain(pitch - mouseDeltaY() * 0.12, -85, 85);
  setRotation3D(0, yaw, 0);
  cam.setRotation3D(pitch, 0, 0);

  var f = 0, r = 0;
  if (keyDown("w")) { f -= 1; }
  if (keyDown("s")) { f += 1; }
  if (keyDown("a")) { r -= 1; }
  if (keyDown("d")) { r += 1; }
  if (f !== 0 || r !== 0) { move3D(r * speed, 0, f * speed); }
  moveAndSlide3D();

  // pick the key up when you look at it and press E
  if (key.isValid() && isLookingAt(key, 3) && keyWentDown("e")) {
    key.destroy();
    giveItem("key");
    showMessage("You found a key!");
  }
  // open the door (only with the key)
  if (isLookingAt(door, 3) && keyWentDown("e")) {
    if (takeItem("key")) { setGlobal("doorOpen", true); showMessage("The door opens..."); }
    else { showMessage("The door is locked."); }
  }
  if (getGlobal("doorOpen", false)) { door.moveTowards(door.x, 5, door.z, 3); }

  // Granny caught you
  if (granny.flatDistanceTo(self) < 1.3) { showMessage("Granny got you!", 5); }
}

Granny script:

// Attach to Granny (a CharacterBody3D with a CollisionShape3D).
var player;
var route = [vec3(-6, 0, -6), vec3(6, 0, -6), vec3(6, 0, 6), vec3(-6, 0, 6)];
var angry = 0;

function start() {
  player = getNode3D("Player");
}

function update(dt) {
  if (canSee(player, 14, 130)) { angry = 4; }     // remember the player for 4 seconds
  if (angry > 0) {
    angry -= dt;
    chase(player, 3.6, 1);                         // runs after you, sliding along walls
  } else {
    patrol(route, 1.6, 1.5);                       // walks around the house
  }
}

Tips: chase walks straight at the target and slides along walls, it does not find a way around them, so keep rooms simple or give Granny a patrol route through the doors. Use node.isTouching(other, 0.5) for generous pick-up distances, and flatDistanceTo to ignore height. Y is up and forward is -Z.

Horror mood: fog, darkness, flashlight, jump scare

// Dark, scary mood: black sky, thick fog, almost no light except your flashlight.
// In the editor: add a SpotLight3D called "Torch" as a child of the Camera3D.
var torch;
function start() {
  torch = getNode3D("Torch");
  World3D.setSkyColor("#05070a");
  World3D.setFog(0.1, "#05070a");          // you only see a few metres
  World3D.setAmbientLight("#1a1f2b", 0.15); // shadows are almost black
  getNode3D("Sun").setLight(0.05);          // dim the sun from the template
  torch.setLight(4, "#ffeecc", 18);
}
function update() {
  // power cut: the torch flickers a few frames every second
  if (World3D.frameCount % 60 < 4) { torch.setLight(0.3); } else { torch.setLight(4); }
}
// jump scare: call this when the monster appears
function scare() { camera3D.shake(0.25, 0.8); showMessage("Behind you!", 2); }

Fog, ambient light and the sky colour change the whole world; node.setLight(energy, color, range) changes any light, so a flashlight, a flickering lamp or a power cut is one line. Add sounds with playSound, playSoundAt (3D, gets louder when close) and duckMusic.

Other useful 3D commands: createObject3D("box", x, y, z) creates objects at run time, spawn3D("res://scenes/enemy.tscn", vec3(0, 0, -5)) instances a scene, getNode3D("Path") returns a reference whose position, rotation and scale can be read and assigned, camera3D.follow(node, 0.1) makes the camera follow.

Command reference

Click a name to jump to it, or type in the search box above. Watch out notes show the mistakes beginners make most.

Lifecycle callbacks 6

#function start() { ... }

callback2D + 3DGame Lab-style

Optional. Called once when the game starts (after the whole script has run once). Use it to create sprites and set up the game.

No parameters.

Returns: void – Nothing.

var player;
function start() {
  player = createSprite(200, 200, 40, 40);
  player.shapeColor = "blue";
}

Watch out: Game Lab has no start(): there the top of the script runs once. In VYOM Engine code outside any function also runs once (so both styles work). Do not call start() yourself.

#function update(dt) { ... }

callback2D + 3DGame Lab-style

Optional. Called every frame, 30 times per second by default in 2D (60 in 3D). Game Lab's draw() loop is the same idea; update() runs first, then draw().

NameTypeRequiredWhat it is
dtnumberoptionalSeconds since the previous frame (3D scripts mostly use it)

Returns: void – Nothing.

function update() {
  if (keyDown("RIGHT_ARROW")) { player.x += 4; }
}

Watch out: Putting createSprite() inside update() creates a new sprite every frame. Create sprites once in start() or at the top of the script.

#function draw() { ... }

callback2DGame Lab

Optional. Called every frame after update(). Like in Game Lab, draw() normally clears the screen with background() and ends with drawSprites().

No parameters.

Returns: void – Nothing.

function draw() {
  background("white");
  drawSprites();
}

Watch out: The canvas is cleared at the beginning of every frame (this is how Game Lab works too). Anything you draw must be drawn again each frame, inside draw() or update().

#function onCollision(other) { ... }

callback2D + 3DVYOM

Called on a script attached to a physics body (CharacterBody, RigidBody, StaticBody) when the body starts touching another body. `other` is a node reference.

NameTypeRequiredWhat it is
otherNodeyesThe node that was touched

Returns: void – Nothing.

function onCollision(other) {
  if (other.name === "Coin") { other.destroy(); }
}

Watch out: Only works for scripts attached to a node in the scene tree. For sprites made with createSprite() use sprite.collide()/overlap() instead.

#function onAreaEntered(other) { ... }

callback2D + 3DVYOM

Called on a script attached to an Area2D/Area3D node when another body enters the area.

NameTypeRequiredWhat it is
otherNodeyesThe node that entered

Returns: void – Nothing.

function onAreaEntered(other) {
  print(other.name + " entered the zone");
}

Watch out: The area needs a CollisionShape child with a shape, and the other body must be on a matching collision layer.

#function onAreaExited(other) { ... }

callback2D + 3DVYOM

Called on a script attached to an Area2D/Area3D node when another body leaves the area.

NameTypeRequiredWhat it is
otherNodeyesThe node that left

Returns: void – Nothing.

function onAreaExited(other) {
  print(other.name + " left the zone");
}

Watch out: Same requirements as onAreaEntered.

Sprites 11

#createSprite(x?, y?, width?, height?)

function2DGame Lab

Creates a sprite: a movable rectangle (or animation) with position, velocity and collision. A new sprite gets a random color.

NameTypeRequiredWhat it is
xnumberoptionalHorizontal center (default 0)
ynumberoptionalVertical center (default 0)
widthnumberoptionalWidth in pixels (default 100)
heightnumberoptionalHeight in pixels (default 100)

Returns: Sprite – The new sprite

var ball = createSprite(200, 100, 30, 30);
ball.shapeColor = "red";
ball.velocityY = 2;

Watch out: x and y are the CENTER of the sprite, not the top-left corner. Forgetting drawSprites() in draw() means nothing appears.

#createGroup()

function2DGame Lab

Creates an empty group (a list of sprites with helpers). Groups are used to handle many sprites at once, for example to make all enemies collide with the player.

No parameters.

Returns: Group – An empty group

var enemies = createGroup();
enemies.add(createSprite(50, 50, 20, 20));
enemies.add(createSprite(150, 50, 20, 20));
enemies.setVelocityEach(0, 2);

Watch out: A sprite can be in many groups. Removing a sprite from a group does not destroy it; call sprite.destroy() for that.

#createEdgeSprites()

function2DGame Lab

Creates four invisible, immovable sprites around the edges of the screen and defines the globals edges, leftEdge, rightEdge, topEdge and bottomEdge.

No parameters.

Returns: void

createEdgeSprites();
var ball = createSprite(200, 200, 20, 20);
ball.velocityX = 3;
function update() {
  ball.bounceOff(edges);
}

Watch out: Call it once, after the world size is known (at the start). The edges are not drawn.

#drawSprites(group?)

function2DGame Lab

Draws all sprites (sorted by depth) with the camera applied. Call it once per frame inside draw() after background().

NameTypeRequiredWhat it is
groupGroupoptionalOnly draw this group (default: all sprites)

Returns: void

function draw() {
  background("lightblue");
  drawSprites();
}

Watch out: Anything drawn after drawSprites() (text, shapes) appears on top of the sprites; anything before appears behind.

#drawSprite(sprite)

function2DGame Lab

Draws a single sprite.

NameTypeRequiredWhat it is
spriteSpriteyesThe sprite to draw

Returns: void

function draw() {
  background("white");
  drawSprite(player);
}

Watch out: Sprites are only drawn when you call drawSprites() or drawSprite(); they are never drawn automatically.

#removeSprite(sprite)

function2DGame Lab-style

Removes (destroys) a sprite. Same as sprite.destroy().

NameTypeRequiredWhat it is
spriteSpriteyesThe sprite to remove

Returns: void

removeSprite(ball);

Watch out: After removal the sprite object still exists in your variable but is not drawn or updated. Check sprite.removed if unsure.

#edges

object2DGame Lab

Group with the four edge sprites. Defined after createEdgeSprites().

Type: Group

createEdgeSprites();
ball.bounceOff(edges);

Watch out: Undefined until createEdgeSprites() has been called.

#leftEdge

object2DGame Lab

The invisible sprite at the left edge. Defined after createEdgeSprites().

Type: Sprite

createEdgeSprites();
player.collide(leftEdge);

Watch out: Edges are immovable and invisible.

#rightEdge

object2DGame Lab

The invisible sprite at the right edge.

Type: Sprite

createEdgeSprites();
player.collide(rightEdge);

Watch out: Defined after createEdgeSprites().

#topEdge

object2DGame Lab

The invisible sprite at the top edge.

Type: Sprite

createEdgeSprites();
player.collide(topEdge);

Watch out: Defined after createEdgeSprites().

#bottomEdge

object2DGame Lab

The invisible sprite at the bottom edge.

Type: Sprite

createEdgeSprites();
player.collide(bottomEdge);

Watch out: Defined after createEdgeSprites().

Sprite properties 32

#sprite.x

property2DGame Lab

Horizontal position of the sprite's center, in pixels.

Type: number

player.x = player.x + 3;

Watch out: x grows to the right. 0 is the left edge of the canvas.

#sprite.y

property2DGame Lab

Vertical position of the sprite's center, in pixels.

Type: number

player.y = 100;

Watch out: y grows DOWNWARD like on a screen, so a bigger y is lower.

#sprite.width

property2DGame Lab

Width of the sprite in pixels (before scale).

Type: number

player.width = 80;

Watch out: Use scale to resize while keeping the proportions.

#sprite.height

property2DGame Lab

Height of the sprite in pixels (before scale).

Type: number

player.height = 20;

Watch out: Collision uses width/height (or the collider you set with setCollider).

#sprite.scale

property2DGame Lab

Size multiplier. 1 = normal size, 2 = twice as big.

Type: number

player.scale = 1.5;

Watch out: Scale also scales the collision area.

#sprite.rotation

property2DGame Lab

Rotation in degrees (clockwise). The collision box does not rotate.

Type: number

player.rotation = 45;

Watch out: The collider ignores rotation: a rotated sprite still collides as an upright box.

#sprite.rotationSpeed

property2DGame Lab

Degrees added to rotation each frame.

Type: number

fan.rotationSpeed = 5;

Watch out: It is per frame, not per second.

#sprite.depth

property2DGame Lab

Draw order. Sprites with a higher depth are drawn on top. New sprites get the highest depth so far plus one.

Type: number

background1.depth = 0;
player.depth = 10;

Watch out: Depth only affects drawing, not collisions.

#sprite.visible

property2DGame Lab

When false the sprite is not drawn (it still moves and collides).

Type: boolean

hint.visible = false;

Watch out: An invisible sprite still collides. Destroy it if it should be gone.

#sprite.lifetime

property2DGame Lab

Frames until the sprite is automatically destroyed. Default -1 means forever; the countdown only runs while the value is above 0.

Type: number

spark.lifetime = 30;

Watch out: Setting lifetime to 0 does nothing; use destroy().

#sprite.life

property2DGame Lab-style

Alias of lifetime (p5.play name).

Type: number

spark.life = 30;

Watch out: Prefer lifetime.

#sprite.debug

property2DGame Lab

Draws the collision shape over the sprite, handy for checking colliders.

Type: boolean

player.debug = true;

Watch out: Remove it when you are done debugging.

#sprite.shapeColor

property2DGame Lab

Fill color of a sprite that has no animation. Accepts color names, "#rrggbb", rgb()/rgba() strings and hsl().

Type: string

player.shapeColor = "orange";
player.shapeColor = rgb(255, 0, 128);

Watch out: Has no effect on a sprite showing an animation.

#sprite.velocityX

property2DGame Lab

Horizontal speed in pixels per frame.

Type: number

ball.velocityX = 4;

Watch out: Speed is per frame (30 frames per second by default), not per second.

#sprite.velocityY

property2DGame Lab

Vertical speed in pixels per frame. Positive moves down.

Type: number

ball.velocityY = -6;

Watch out: A jump needs a NEGATIVE velocityY (up).

#sprite.position

property2DGame Lab-style

Object with x and y that reads and writes the sprite position.

Type: object

player.position.x = 100;

Watch out: Reads/writes the sprite directly, it is not a copy.

#sprite.velocity

property2DGame Lab-style

Object with x and y that reads and writes velocityX/velocityY.

Type: object

ball.velocity.x = 3;

Watch out: Reads/writes the sprite directly, it is not a copy.

#sprite.previousX

property2DGame Lab-style

x position at the start of the previous frame's movement step.

Type: number

var moved = player.x - player.previousX;

Watch out: Read-only in practice.

#sprite.previousY

property2DGame Lab-style

y position at the start of the previous frame's movement step.

Type: number

var moved = player.y - player.previousY;

Watch out: Read-only in practice.

#sprite.previousPosition

property2DGame Lab-style

Object {x, y} with the previous position.

Type: object

print(player.previousPosition.x);

Watch out: A copy: changing it does nothing.

#sprite.maxSpeed

property2DGame Lab

Speed limit in pixels per frame. -1 (default) means no limit.

Type: number

ball.maxSpeed = 8;

Watch out: Applied every frame before the sprite moves.

#sprite.friction

property2DGame Lab

Fraction of speed lost per frame (0 = none, 0.1 = slows 10% each frame).

Type: number

puck.friction = 0.05;

Watch out: Values above 1 stop the sprite instantly.

#sprite.immovable

property2DGame Lab

An immovable sprite is not pushed by collide(), bounce() or displace() and ignores World.gravity.

Type: boolean

wall.immovable = true;

Watch out: It still moves if you give it a velocity.

#sprite.mass

property2DGame Lab

Used by bounce() to decide how much each sprite is pushed. Default 1.

Type: number

heavy.mass = 5;

Watch out: Only matters for bounce()/bounceOff().

#sprite.bounciness

property2DGame Lab

How much speed is kept in bounce() (0 to 1). Default 1.

Type: number

ball.bounciness = 0.8;

Watch out: The pair uses the product of both sprites.

#sprite.mirrorX

property2DGame Lab-style

Flips the sprite horizontally when true (or -1).

Type: boolean

player.mirrorX = true;

Watch out: Game Lab's mirrorX(-1) function style is not used: assign to the property.

#sprite.mirrorY

property2DGame Lab-style

Flips the sprite vertically when true (or -1).

Type: boolean

player.mirrorY = true;

Watch out: Assign to the property.

#sprite.animation

property2DGame Lab

The animation the sprite is currently showing (or null).

Type: Animation

print(player.animation.getFrame());

Watch out: null until setAnimation()/addAnimation() was used.

#sprite.animations

property2DGame Lab-style

Map of label to Animation for the animations added to this sprite.

Type: object

print(Object.keys(player.animations));

Watch out: Use getAnimation(label) for reading a single one.

#sprite.groups

property2DGame Lab-style

List of groups the sprite belongs to.

Type: Group[]

print(player.groups.length);

Watch out: It is a copy; use group.add/remove to change membership.

#sprite.removed

property2DGame Lab-style

True after the sprite was destroyed.

Type: boolean

if (!enemy.removed) { enemy.x += 1; }

Watch out: Check it before using a sprite that another script might have destroyed.

#sprite.id

property2DGame Lab-style

Unique number of the sprite.

Type: number

print(player.id);

Watch out: Not reused.

Sprite methods 41

#sprite.setAnimation(label, animation?)

method2DGame Lab

Shows the animation with this label. If an Animation object is passed it is added first. With only a label it first looks at animations added to this sprite and then at animations saved in the project's animations/ folder (made with the Sprite Sheet Animation Editor).

NameTypeRequiredWhat it is
labelstringyesName of an animation
animationAnimationoptionalAn animation to register under this label first

Returns: void

var hero = createSprite(100, 100);
hero.setAnimation("walk");

Watch out: If the label does not exist you get a warning in the Output panel and the sprite keeps its old look.

#sprite.addAnimation(label, animation)

method2DGame Lab

Adds an animation to the sprite under a label. The first animation added is shown automatically.

NameTypeRequiredWhat it is
labelstringyesName to use later
animationAnimationyesAnimation from loadAnimation()

Returns: Sprite

hero.addAnimation("idle", loadAnimation("idle1.png", "idle2.png"));

Watch out: Adding does not switch to it when another animation is already showing; call changeAnimation() or setAnimation().

#sprite.addImage(label, image)

method2DGame Lab-style

Adds a single image as a one-frame animation.

NameTypeRequiredWhat it is
labelstringyesName
imageImageyesImage from loadImage()

Returns: Sprite

var img = loadImage("assets/tree.png");
var tree = createSprite(50, 50);
tree.addImage("tree", img);

Watch out: Use loadImage() first; passing a file name string does not work.

#sprite.getAnimation(label)

method2DGame Lab-style

Returns the animation stored under this label, or undefined.

NameTypeRequiredWhat it is
labelstringyesName

Returns: Animation

var a = hero.getAnimation("walk");
if (a) { a.frameDelay = 2; }

Watch out: Returns undefined (not an error) for an unknown label.

#sprite.changeAnimation(label)

method2DGame Lab

Switches to a previously added animation and rewinds it.

NameTypeRequiredWhat it is
labelstringyesName of an animation already on this sprite

Returns: void

if (keyDown("SPACE")) { hero.changeAnimation("jump"); }

Watch out: Calling it every frame restarts the animation each frame; only change when the state changes.

#sprite.setCollider(type, offsetX?, offsetY?, width_or_radius?, height?)

method2DGame Lab

Sets the shape used for collisions. Game Lab calls: setCollider("circle", 0, 0, 20) or setCollider("rectangle", 0, 0, 40, 40). setCollider("auto") makes the box exactly as big as the visible (non-transparent) art of the current picture, so a big image with empty space around the character only touches when the character itself touches.

NameTypeRequiredWhat it is
typestringyes"rectangle", "circle" or "auto" (a box that hugs the visible pixels of the picture)
offsetXnumberoptionalCollider center offset from the sprite center
offsetYnumberoptionalOffset
width_or_radiusnumberoptionalRadius for "circle", width for "rectangle"
heightnumberoptionalHeight for "rectangle"

Returns: Sprite

ball.setCollider("circle", 0, 0, 15);
ball.debug = true;

Watch out: Arguments are offset X, offset Y, then size. Rotation is ignored by colliders.

#sprite.collide(target, callback?)

method2DGame Lab

If the sprites overlap, pushes this sprite out of the target (and stops its motion into it). Returns true if they collided.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group to collide with
callbackfunctionoptionalCalled as callback(sprite, other) on each hit

Returns: boolean

player.collide(wall);
player.collide(coins, function (p, coin) { coin.destroy(); });

Watch out: collide only moves THIS sprite. Use bounce for both, displace to push the other. Call it every frame in update().

#sprite.overlap(target, callback?)

method2DGame Lab

Detects overlap without moving anything. Returns true when they overlap and calls the callback for each overlapping sprite.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group
callbackfunctionoptionalCalled as callback(sprite, other)

Returns: boolean

player.overlap(coins, function (p, c) { c.destroy(); score++; });

Watch out: overlap does not push. If sprites must not pass through each other use collide.

#sprite.bounce(target, callback?)

method2DGame Lab

Both sprites bounce off each other like balls (uses mass and bounciness; immovable sprites do not move).

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group
callbackfunctionoptionalCalled as callback(sprite, other)

Returns: boolean

ball.bounce(paddle);

Watch out: Immovable sprites are never pushed; set wall.immovable = true.

#sprite.bounceOff(target, callback?)

method2DGame Lab

Game Lab name for bounce(): identical.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group
callbackfunctionoptionalCalled as callback(sprite, other)

Returns: boolean

ball.bounceOff(edges);

Watch out: Same as bounce.

#sprite.displace(target, callback?)

method2DGame Lab

This sprite pushes the target out of the way (the opposite of collide).

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group
callbackfunctionoptionalCalled as callback(sprite, other)

Returns: boolean

pusher.displace(boxes);

Watch out: Immovable targets are not moved.

#sprite.isTouching(target)

method2DGame Lab

True if this sprite touches or overlaps the target (edges touching count).

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group

Returns: boolean

if (player.isTouching(door)) { print("at the door"); }

Watch out: It only tells you; it does not stop movement. Use collide for that.

#sprite.isColliding(target)

method2DGame Lab-style

Same as isTouching().

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group

Returns: boolean

if (player.isColliding(spikes)) { lives--; }

Watch out: See isTouching.

#sprite.isOverlapping(target)

method2DGame Lab-style

True only if the sprites really overlap (not just touch).

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group

Returns: boolean

if (player.isOverlapping(zone)) { print("inside"); }

Watch out: Edges that only touch are not overlapping.

#sprite.touched(target)

method2DVYOM

True when this sprite HAS touched the target before and is NOT touching it right now. isTouching() is only true while they touch; touched() becomes true when they separate and stays true afterwards (it is false again while they touch).

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesSprite or group

Returns: boolean

function draw() {
  if (player.touched(coin)) {
    print("the player already visited the coin");
  }
}

Watch out: Call it every frame (for example in draw()): it starts watching the pair the first time you call it, so contact before that first call does not count. It is false until the first touch has ended.

#sprite.setSpeed(speed, direction?)

method2DGame Lab-style

Sets velocityX/velocityY from a speed and a direction in degrees.

NameTypeRequiredWhat it is
speednumberyesPixels per frame
directionnumberoptionalDegrees (0 = right, 90 = down). Default: current direction

Returns: Sprite

ball.setSpeed(5, 45);

Watch out: Angles are measured clockwise on screen: 0 right, 90 down, 180 left, 270 up.

#sprite.setSpeedAndDirection(speed, direction)

method2DGame Lab

Game Lab name for setSpeed(speed, direction).

NameTypeRequiredWhat it is
speednumberyesPixels per frame
directionnumberyesDegrees

Returns: Sprite

ball.setSpeedAndDirection(4, 90);

Watch out: Direction 90 moves DOWN.

#sprite.setVelocity(vx, vy?)

method2DGame Lab

Sets velocityX and velocityY at once.

NameTypeRequiredWhat it is
vxnumberyesHorizontal speed
vynumberoptionalVertical speed

Returns: Sprite

ball.setVelocity(2, -3);

Watch out: Speeds are per frame.

#sprite.addSpeed(speed, direction)

method2DGame Lab-style

Adds speed in a direction to the current velocity (an acceleration).

NameTypeRequiredWhat it is
speednumberyesPixels per frame to add
directionnumberyesDegrees

Returns: Sprite

rocket.addSpeed(0.2, 270);

Watch out: Keeps growing every call; use maxSpeed or limitSpeed to cap it.

#sprite.getSpeed()

method2DGame Lab-style

Returns the current speed in pixels per frame.

No parameters.

Returns: number

print(ball.getSpeed());

Watch out: Always positive.

#sprite.getDirection()

method2DGame Lab-style

Returns the current direction of motion in degrees.

No parameters.

Returns: number

print(ball.getDirection());

Watch out: Returns 0 for a sprite that is not moving.

#sprite.pointTo(x, y)

method2DGame Lab

Rotates the sprite so it points at a position (rotation in degrees).

NameTypeRequiredWhat it is
xnumberyesTarget x
ynumberyesTarget y

Returns: Sprite

turret.pointTo(mouseX, mouseY);

Watch out: Art is assumed to point to the right at rotation 0.

#sprite.attractionPoint(force, x, y)

method2DGame Lab-style

Accelerates the sprite towards a point.

NameTypeRequiredWhat it is
forcenumberyesSpeed added per frame
xnumberyesTarget x
ynumberyesTarget y

Returns: Sprite

bee.attractionPoint(0.3, mouseX, mouseY);
bee.limitSpeed(5);

Watch out: Without limitSpeed() or friction the sprite keeps accelerating and overshoots.

#sprite.limitSpeed(max)

method2DGame Lab-style

Scales the velocity down if the speed is above max.

NameTypeRequiredWhat it is
maxnumberyesMaximum speed

Returns: Sprite

bee.limitSpeed(5);

Watch out: One time check; call again after adding speed.

#sprite.destroy()

method2DGame Lab

Removes the sprite from the game and from all groups.

No parameters.

Returns: void

if (bullet.y < 0) { bullet.destroy(); }

Watch out: Do not keep using the sprite afterwards (check sprite.removed).

#sprite.remove()

method2DGame Lab-style

Same as destroy().

No parameters.

Returns: void

enemy.remove();

Watch out: See destroy.

#sprite.mouseIsOver()

method2DGame Lab-style

True while the mouse pointer is over this sprite (hovering). Same as mouseIsOver(sprite).

No parameters.

Returns: boolean

if (button.mouseIsOver()) { button.shapeColor = "yellow"; } else { button.shapeColor = "gray"; }

Watch out: It tests the sprite collider, so setCollider() changes the hover area.

#sprite.mousePressedOver()

method2DGame Lab-style

True for the one frame in which the left mouse button is clicked while the pointer is over this sprite. Same as mousePressedOver(sprite).

No parameters.

Returns: boolean

if (playButton.mousePressedOver()) { gameState = "play"; }

Watch out: Only one frame: it fires once per click. Use mouseHeldOver() for dragging.

#sprite.mouseHeldOver()

method2DGame Lab-style

True every frame while the left mouse button is held down and the pointer is over this sprite.

No parameters.

Returns: boolean

if (slider.mouseHeldOver()) { slider.x = mouseX; }

Watch out: Becomes false if the pointer slides off the sprite while dragging; use a bigger collider for fast drags.

#sprite.mouseReleasedOver()

method2DGame Lab-style

True for the one frame in which the left mouse button is released over this sprite.

No parameters.

Returns: boolean

if (card.mouseReleasedOver()) { print("dropped"); }

Watch out: One frame only.

#sprite.distanceTo(x_or_target, y?)

method2DGame Lab-style

Distance in pixels from this sprite to a point or another sprite.

NameTypeRequiredWhat it is
x_or_targetnumber|SpriteyesA number (then pass y too) or a sprite
ynumberoptionaly when the first argument is a number

Returns: number

if (enemy.distanceTo(player) < 100) { enemy.moveTowards(player, 2); }

Watch out: With numbers give both x and y: sprite.distanceTo(200, 100). Returns NaN for bad arguments.

#sprite.angleTo(x_or_target, y?)

method2DGame Lab-style

Direction in degrees from this sprite to a point or sprite (0 = right, 90 = down). Handy with setSpeed().

NameTypeRequiredWhat it is
x_or_targetnumber|SpriteyesA number (then pass y too) or a sprite
ynumberoptionaly when the first argument is a number

Returns: number

bullet.setSpeed(8, shooter.angleTo(mouseX, mouseY));

Watch out: Angles use the Game Lab convention: 90 is DOWN.

#sprite.moveTowards(x_or_target, y_or_speed, speed?)

method2DGame Lab-style

Moves the sprite straight towards a point or sprite by at most speed pixels and never overshoots. Returns true when it has arrived.

NameTypeRequiredWhat it is
x_or_targetnumber|SpriteyesA number (then pass y and speed) or a sprite (then pass speed)
y_or_speednumberyesy, or the speed when the first argument is a sprite
speednumberoptionalPixels to move this frame

Returns: boolean

function update() {
  enemy.moveTowards(player, 2);
  if (enemy.isTouching(player)) { print("caught!"); }
}

Watch out: Call it every frame (in update()). It changes x and y directly, so velocity is not used.

#sprite.setPosition(x, y)

method2DGame Lab-style

Puts the sprite at x, y.

NameTypeRequiredWhat it is
xnumberyesNew x
ynumberyesNew y

Returns: Sprite

player.setPosition(200, 350);

Watch out: Same as setting x and y.

#sprite.setSize(width, height?)

method2DGame Lab-style

Sets width and height.

NameTypeRequiredWhat it is
widthnumberyesNew width
heightnumberoptionalNew height (default: same as width)

Returns: Sprite

box.setSize(60, 30);

Watch out: This changes the drawn rectangle; the default collider follows it.

#sprite.hide()

method2DGame Lab-style

Makes the sprite invisible (visible = false). Invisible sprites still move and collide.

No parameters.

Returns: Sprite

secretDoor.hide();

Watch out: Use destroy() to really remove a sprite.

#sprite.show()

method2DGame Lab-style

Makes the sprite visible again.

No parameters.

Returns: Sprite

secretDoor.show();

Watch out: Opposite of hide().

#sprite.isTouchingEdges()

method2DGame Lab-style

True if the sprite touches or crosses any side of the screen (0..World.width, 0..World.height).

No parameters.

Returns: boolean

if (ball.isTouchingEdges()) { ball.setSpeed(0); }

Watch out: It uses the collider, not the picture.

#sprite.isOffScreen()

method2DGame Lab-style

True if the sprite is completely outside the screen.

No parameters.

Returns: boolean

if (bullet.isOffScreen()) { bullet.destroy(); }

Watch out: A sprite that is only partly outside is not off screen.

#sprite.stayOnScreen()

method2DGame Lab-style

Pushes the sprite back inside the screen so it can never leave it.

No parameters.

Returns: Sprite

function update() {
  if (keyDown("right")) { player.x += 4; }
  player.stayOnScreen();
}

Watch out: Call it after you move the sprite. It does not change the velocity.

#sprite.wrapAround()

method2DGame Lab-style

When the sprite has fully left one side of the screen it re-appears on the opposite side (like Asteroids).

No parameters.

Returns: Sprite

ship.wrapAround();

Watch out: Call it every frame after moving.

Groups 37

#group.length

property2DGame Lab

Number of sprites in the group. A group is also a normal JavaScript array, so [], forEach, filter, map... all work.

Type: number

for (var i = 0; i < enemies.length; i++) {
  enemies[i].y += 1;
}

Watch out: Destroying sprites while looping forwards skips some; loop backwards or use destroyEach().

#group.add(sprite)

method2DGame Lab

Adds a sprite to the group (ignored if already inside).

NameTypeRequiredWhat it is
spriteSpriteyesSprite to add

Returns: Group

enemies.add(enemy);

Watch out: Adding the same sprite twice does nothing.

#group.remove(sprite)

method2DGame Lab

Removes the sprite from the group only (it is NOT destroyed). Returns true if it was in the group.

NameTypeRequiredWhat it is
spriteSpriteyesSprite to remove

Returns: boolean

enemies.remove(enemy);

Watch out: Use sprite.destroy() to delete the sprite.

#group.contains(sprite)

method2DGame Lab

True if the sprite is in the group.

NameTypeRequiredWhat it is
spriteSpriteyesSprite to look for

Returns: boolean

if (enemies.contains(s)) { print("enemy"); }

Watch out: It checks identity, not position.

#group.get(index)

method2DGame Lab

Returns the sprite at an index (same as group[index]).

NameTypeRequiredWhat it is
indexnumberyes0-based index

Returns: Sprite

var first = enemies.get(0);

Watch out: Indexes start at 0; out of range gives undefined.

#group.toArray()

method2DGame Lab-style

Returns a plain array copy of the sprites.

No parameters.

Returns: Sprite[]

var list = enemies.toArray();

Watch out: It is a copy.

#group.clear()

method2DGame Lab

Empties the group without destroying the sprites.

No parameters.

Returns: void

enemies.clear();

Watch out: Use destroyEach() to also delete the sprites.

#group.maxDepth()

method2DGame Lab

Highest depth among the sprites (0 if empty).

No parameters.

Returns: number

hud.depth = allSprites.maxDepth() + 1;

Watch out: Returns 0 for an empty group.

#group.minDepth()

method2DGame Lab

Lowest depth among the sprites (99999 if empty).

No parameters.

Returns: number

back.depth = allSprites.minDepth() - 1;

Watch out: Returns 99999 for an empty group.

#group.setPropertyEach(property, value)

method2DGame Lab-style

Sets a property on every sprite.

NameTypeRequiredWhat it is
propertystringyesProperty name
valueanyyesValue to set

Returns: void

enemies.setPropertyEach("scale", 0.5);

Watch out: The property name is a string, with quotes.

#group.setVelocityEach(vx, vy?)

method2DGame Lab

Sets the velocity of every sprite.

NameTypeRequiredWhat it is
vxnumberyesHorizontal speed
vynumberoptionalVertical speed

Returns: void

enemies.setVelocityEach(0, 2);

Watch out: Speeds are per frame.

#group.setColorEach(color)

method2DGame Lab

Sets shapeColor of every sprite.

NameTypeRequiredWhat it is
colorstringyesColor

Returns: void

coins.setColorEach("gold");

Watch out: Does nothing for sprites showing animations.

#group.setLifetimeEach(frames)

method2DGame Lab

Sets lifetime of every sprite.

NameTypeRequiredWhat it is
framesnumberyesFrames to live

Returns: void

sparks.setLifetimeEach(30);

Watch out: Frames, not seconds.

#group.setAnimationEach(label, animation?)

method2DGame Lab

Calls setAnimation on every sprite.

NameTypeRequiredWhat it is
labelstringyesAnimation label
animationAnimationoptionalOptional animation to register

Returns: void

enemies.setAnimationEach("walk");

Watch out: Each sprite needs the label unless it is saved in the animations folder.

#group.destroyEach()

method2DGame Lab

Destroys every sprite in the group.

No parameters.

Returns: void

bullets.destroyEach();

Watch out: The group ends up empty.

#group.collide(target, callback?)

method2DGame Lab

Runs sprite.collide(target) for every sprite in the group.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget
callbackfunctionoptionalcallback(sprite, other)

Returns: boolean

enemies.collide(walls);

Watch out: Pairs inside the same group do not interact unless you pass the group as target.

#group.overlap(target, callback?)

method2DGame Lab

Runs sprite.overlap(target) for every sprite.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget
callbackfunctionoptionalcallback(sprite, other)

Returns: boolean

bullets.overlap(enemies, function (b, e) { b.destroy(); e.destroy(); });

Watch out: The callback gets (sprite from this group, other).

#group.bounce(target, callback?)

method2DGame Lab

Runs sprite.bounce(target) for every sprite.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget
callbackfunctionoptionalcallback(sprite, other)

Returns: boolean

balls.bounce(balls);

Watch out: Bouncing a group off itself works, each pair is resolved.

#group.bounceOff(target, callback?)

method2DGame Lab

Same as group.bounce().

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget
callbackfunctionoptionalcallback(sprite, other)

Returns: boolean

balls.bounceOff(edges);

Watch out: See bounce.

#group.displace(target, callback?)

method2DGame Lab

Runs sprite.displace(target) for every sprite.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget
callbackfunctionoptionalcallback(sprite, other)

Returns: boolean

pushers.displace(boxes);

Watch out: See sprite.displace.

#group.isTouching(target)

method2DGame Lab

True if any sprite in the group touches the target.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget

Returns: boolean

if (enemies.isTouching(player)) { gameOver(); }

Watch out: Touching is inclusive of edges.

#group.isColliding(target)

method2DGame Lab-style

Same as isTouching.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget

Returns: boolean

if (enemies.isColliding(player)) { gameOver(); }

Watch out: See isTouching.

#group.isOverlapping(target)

method2DGame Lab-style

True if any sprite really overlaps the target.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget

Returns: boolean

if (zone.isOverlapping(player)) { print("in"); }

Watch out: See sprite.isOverlapping.

#group.touched(target)

method2DVYOM

True when any sprite of the group HAS touched the target before and none of them is touching it right now.

NameTypeRequiredWhat it is
targetSprite|Group|NodeyesTarget

Returns: boolean

if (enemies.touched(wall)) { print("an enemy reached the wall"); }

Watch out: Call it every frame. See sprite.touched.

#World.allSprites

property2DGame Lab

Group containing every sprite that has been created.

Type: Group

print(World.allSprites.length);

Watch out: It contains sprites that are invisible too.

#group.setDepthEach(depth)

method2DGame Lab

Sets depth of every sprite (higher depth draws on top).

NameTypeRequiredWhat it is
depthnumberyesDepth

Returns: void

clouds.setDepthEach(-1);

Watch out: Depth is the draw order, not 3D depth.

#group.setRotationEach(degrees)

method2DGame Lab

Sets rotation of every sprite.

NameTypeRequiredWhat it is
degreesnumberyesRotation

Returns: void

arrows.setRotationEach(90);

Watch out: Degrees.

#group.setRotationSpeedEach(degrees)

method2DGame Lab

Sets rotationSpeed of every sprite.

NameTypeRequiredWhat it is
degreesnumberyesDegrees per frame

Returns: void

stars.setRotationSpeedEach(3);

Watch out: Per frame.

#group.setScaleEach(scale)

method2DGame Lab

Sets scale of every sprite.

NameTypeRequiredWhat it is
scalenumberyesScale (1 = normal)

Returns: void

coins.setScaleEach(0.5);

Watch out: 1 is normal size.

#group.setVisibleEach(visible)

method2DGame Lab

Shows or hides every sprite.

NameTypeRequiredWhat it is
visiblebooleanyestrue or false

Returns: void

menuButtons.setVisibleEach(false);

Watch out: Hidden sprites still exist and collide.

#group.setSpeedAndDirectionEach(speed, direction?)

method2DGame Lab

Calls setSpeed(speed, direction) on every sprite.

NameTypeRequiredWhat it is
speednumberyesPixels per frame
directionnumberoptionalDegrees

Returns: void

bullets.setSpeedAndDirectionEach(6, 270);

Watch out: Direction 270 moves UP.

#group.isEmpty()

method2DGame Lab-style

True if the group has no sprites.

No parameters.

Returns: boolean

if (enemies.isEmpty()) { print("you win!"); }

Watch out: Same as length === 0.

#group.first()

method2DGame Lab-style

The first sprite of the group (undefined if empty).

No parameters.

Returns: Sprite

var oldest = enemies.first();

Watch out: Check isEmpty() first.

#group.last()

method2DGame Lab-style

The last sprite of the group (undefined if empty).

No parameters.

Returns: Sprite

var newest = enemies.last();

Watch out: Check isEmpty() first.

#group.random()

method2DGame Lab-style

A random sprite from the group (undefined if empty).

No parameters.

Returns: Sprite

var target = enemies.random();

Watch out: Check isEmpty() first.

#group.mouseIsOver(callback?)

method2DGame Lab-style

True if the mouse is over any sprite of the group.

NameTypeRequiredWhat it is
callbackfunctionoptionalCalled as callback(sprite) for each hovered sprite

Returns: boolean

buttons.mouseIsOver(function (b) { b.shapeColor = "yellow"; });

Watch out: The callback is optional.

#group.mousePressedOver(callback?)

method2DGame Lab-style

True for the frame when any sprite of the group is clicked. The callback tells you which one.

NameTypeRequiredWhat it is
callbackfunctionoptionalCalled as callback(sprite) for each clicked sprite

Returns: boolean

buttons.mousePressedOver(function (b) { print("clicked " + b.id); });

Watch out: One frame per click.

Animations & images 3

#loadAnimation(source...)

function2DGame Lab

Creates an animation from image files, a sprite sheet or an animation saved in the project's animations/ folder. Several file names are shown in order; two file names that end in numbers ("walk_001.png", "walk_004.png") load the whole numbered range.

NameTypeRequiredWhat it is
source...string|SpriteSheetyesFile names ("a1.png","a3.png" loads a numbered sequence), a SpriteSheet (with optional first/last frame numbers), or the label of an animation saved by the Animation Editor

Returns: Animation – A new animation

var run = loadAnimation("assets/run1.png", "assets/run2.png", "assets/run3.png");
player.addAnimation("run", run);
var sheet = loadSpriteSheet("assets/hero.png", 32, 32);
var idle = loadAnimation(sheet, 0, 3);

Watch out: File paths are relative to the project folder (assets/hero.png) or full res:// paths. A wrong path gives an empty animation and a warning. Import the files into the project first.

#loadSpriteSheet(path, frameWidth, frameHeight, count?)

function2DGame Lab

Cuts an image into equally sized frames (left to right, top to bottom). You can also pass an array of {x, y, width, height} frames as second argument. Use it with loadAnimation(sheet).

NameTypeRequiredWhat it is
pathstringyesImage file
frameWidthnumberyesWidth of one frame
frameHeightnumberyesHeight of one frame
countnumberoptionalNumber of frames (default: all)

Returns: SpriteSheet – The sheet

var sheet = loadSpriteSheet("assets/coin.png", 16, 16, 8);
var spin = loadAnimation(sheet);

Watch out: The frame size must divide the image; otherwise the last partial frame is dropped.

#loadImage(path)

function2DGame Lab

Loads an image for use with image() or sprite.addImage().

NameTypeRequiredWhat it is
pathstringyesImage file

Returns: Image – An image object

var bg = loadImage("assets/sky.png");
function draw() {
  image(bg, 0, 0);
  drawSprites();
}

Watch out: The image object has width and height; it is not drawn until you call image().

Animation members 21

#animation.frameDelay

property2DGame Lab

Game frames between two animation frames (default 4). Smaller is faster.

Type: number

run.frameDelay = 2;

Watch out: It counts game frames (30 per second by default), not seconds.

#animation.looping

property2DGame Lab

Whether the animation restarts after the last frame (default true).

Type: boolean

explosion.looping = false;

Watch out: A non-looping animation stops on its last frame.

#animation.visible

property2DGame Lab

Hide the animation without hiding the sprite.

Type: boolean

run.visible = false;

Watch out: The sprite itself still collides.

#animation.scale

property2DGame Lab

Size multiplier of the animation frames.

Type: number

run.scale = 2;

Watch out: Different from sprite.scale, which also scales the collider.

#animation.rotation

property2DGame Lab

Extra rotation in degrees applied to the frames.

Type: number

run.rotation = 90;

Watch out: Added to the sprite's own rotation.

#animation.offX

property2DGame Lab-style

Horizontal drawing offset in pixels.

Type: number

run.offX = 5;

Watch out: Moves only the picture, not the collider.

#animation.offY

property2DGame Lab-style

Vertical drawing offset in pixels.

Type: number

run.offY = -4;

Watch out: Moves only the picture, not the collider.

#animation.tint

property2DGame Lab-style

Color multiplied onto the frames (e.g. "red" for a damage flash).

Type: string

run.tint = "red";

Watch out: Set to null to remove.

#animation.play()

method2DGame Lab

Starts or resumes playing.

No parameters.

Returns: void

run.play();

Watch out: Animations play by default.

#animation.stop()

method2DGame Lab

Pauses the animation on the current frame.

No parameters.

Returns: void

run.stop();

Watch out: It does not rewind; use rewind().

#animation.rewind()

method2DGame Lab

Goes back to the first frame.

No parameters.

Returns: void

run.rewind();

Watch out: Does not change whether it is playing.

#animation.nextFrame()

method2DGame Lab

Shows the next frame (wraps if looping).

No parameters.

Returns: void

run.nextFrame();

Watch out: Use together with stop() for manual control.

#animation.previousFrame()

method2DGame Lab

Shows the previous frame.

No parameters.

Returns: void

run.previousFrame();

Watch out: Wraps only if looping.

#animation.changeFrame(frame)

method2DGame Lab

Jumps to a frame number (clamped).

NameTypeRequiredWhat it is
framenumberyesFrame index

Returns: void

run.changeFrame(2);

Watch out: The first frame is 0.

#animation.getFrame()

method2DGame Lab

Returns the current frame number.

No parameters.

Returns: number

print(run.getFrame());

Watch out: Starts at 0.

#animation.getFrameCount()

method2DGame Lab

Returns how many frames the animation has.

No parameters.

Returns: number

print(run.getFrameCount());

Watch out: 0 means the image files were not found.

#animation.getWidth()

method2DGame Lab

Width of the current frame in pixels.

No parameters.

Returns: number

print(run.getWidth());

Watch out: Frame size, before scaling.

#animation.getHeight()

method2DGame Lab

Height of the current frame in pixels.

No parameters.

Returns: number

print(run.getHeight());

Watch out: Frame size, before scaling.

#animation.isPlaying()

method2DGame Lab

True while the animation advances.

No parameters.

Returns: boolean

if (!run.isPlaying()) { run.play(); }

Watch out: Non-looping animations stop at the end.

#animation.clone()

method2DGame Lab-style

Makes an independent copy (frames are shared, state is separate).

No parameters.

Returns: Animation

var a2 = run.clone();

Watch out: Needed if two sprites should animate independently.

#animation.draw(x, y, rotation?)

method2DGame Lab-style

Draws the current frame at a position (for animations that are not on a sprite). Also advances nothing: call nextFrame yourself.

NameTypeRequiredWhat it is
xnumberyesCenter x
ynumberyesCenter y
rotationnumberoptionalDegrees

Returns: void

run.draw(100, 100);

Watch out: Sprites advance their own animation automatically; plain drawing does not.

Camera & World 21

#camera

object2DGame Lab

The 2D camera. It is on by default and centered on the world; drawSprites() draws through it.

Type: object

camera.x = player.x;
camera.y = player.y;

Watch out: The camera only affects sprites drawn with drawSprites()/drawSprite(), not shapes like rect().

#camera.x

property2DGame Lab

World x position the camera looks at.

Type: number

camera.x = player.x;

Watch out: Start value is the center of the world.

#camera.y

property2DGame Lab

World y position the camera looks at.

Type: number

camera.y = player.y;

Watch out: Start value is the center of the world.

#camera.zoom

property2DGame Lab

Camera zoom (1 = normal, 2 = twice as close).

Type: number

camera.zoom = 2;

Watch out: Zoom 0 or negative is invalid.

#camera.position

property2DGame Lab

Object with x and y for the camera position.

Type: object

camera.position.x = 200;

Watch out: Reads/writes the camera directly.

#camera.on()

method2DGame Lab

Turns the camera on (default).

No parameters.

Returns: void

camera.on();

Watch out: drawSprites() uses the camera only while it is on.

#camera.off()

method2DGame Lab

Turns the camera off: sprites are drawn at their world positions. Good for HUD drawing.

No parameters.

Returns: void

camera.off();
text("Score: " + score, 10, 20);
camera.on();

Watch out: Call camera.on() again for the next frame's sprites.

#camera.follow(sprite, smoothing?)

method2DGame Lab-style

Makes the camera follow a sprite every frame.

NameTypeRequiredWhat it is
spriteSpriteyesSprite to follow
smoothingnumberoptional0.001 to 1 (1 = snap, small = smooth)

Returns: void

camera.follow(player, 0.1);

Watch out: Pass null to stop following.

#camera.mouseX

property2DGame Lab

Mouse x position in world coordinates (taking the camera into account).

Type: number read-only

target.x = camera.mouseX;

Watch out: World.mouseX / mouseX are screen coordinates.

#camera.mouseY

property2DGame Lab

Mouse y position in world coordinates.

Type: number read-only

target.y = camera.mouseY;

Watch out: World.mouseY / mouseY are screen coordinates.

#World

object2DGame Lab

Information and settings of the 2D game world.

Type: object

World.frameRate = 60;
World.gravity = 0.5;

Watch out: World is for 2D; use World3D in 3D scenes.

#World.width

property2DGame Lab

Width of the game screen in pixels (from Project Settings).

Type: number read-only

ball.x = World.width / 2;

Watch out: Game Lab's default is 400; Nova projects set it in Project Settings.

#World.height

property2DGame Lab

Height of the game screen in pixels.

Type: number read-only

ball.y = World.height / 2;

Watch out: See width.

#World.frameCount

property2DGame Lab

Number of frames since the game started.

Type: number read-only

if (World.frameCount % 30 === 0) { spawnEnemy(); }

Watch out: Counts frames, not seconds.

#World.seconds

property2DGame Lab

Whole seconds since the game started.

Type: number read-only

text("Time: " + World.seconds, 10, 20);

Watch out: Rounded down.

#World.frameRate

property2DGame Lab

Frames per second of update()/draw() (default 30). You can assign a new value.

Type: number

World.frameRate = 60;

Watch out: Values above 240 are capped.

#World.gravity

property2DGame Lab

Downward acceleration added to every non-immovable sprite each frame (pixels per frame squared). Default 0.

Type: number

World.gravity = 0.8;

Watch out: Immovable sprites ignore it; set ground.immovable = true.

#World.mouseX

property2DGame Lab

Mouse x in screen coordinates.

Type: number read-only

print(World.mouseX);

Watch out: Same as the global mouseX.

#World.mouseY

property2DGame Lab

Mouse y in screen coordinates.

Type: number read-only

print(World.mouseY);

Watch out: Same as the global mouseY.

#World.camera

property2DGame Lab-style

The camera (same as the global camera).

Type: object read-only

World.camera.zoom = 2;

Watch out: Same object as camera.

#frameRate(fps)

function2DGame Lab

Sets the frame rate of update()/draw(). Same as World.frameRate = fps.

NameTypeRequiredWhat it is
fpsnumberyesFrames per second

Returns: void

frameRate(60);

Watch out: It is a function here; World.frameRate is a property.

Drawing 41

#background(color)

function2DGame Lab

Fills the whole screen with a color. Call it first in draw() to erase the previous frame.

NameTypeRequiredWhat it is
colorstring|numberyesA color name, "#rrggbb", rgb(), or 3 numbers r,g,b

Returns: void

function draw() {
  background("black");
}

Watch out: Call it before drawSprites() or the sprites get covered.

#clear()

function2DGame Lab

Removes everything that has been drawn this frame.

No parameters.

Returns: void

clear();

Watch out: Different from background(): it makes the screen transparent/empty.

#fill(color)

function2DGame Lab

Sets the fill color for the shapes and text drawn afterwards.

NameTypeRequiredWhat it is
colorstring|numberyesColor, or r, g, b (0-255), or one gray number

Returns: void

fill("red");
rect(10, 10, 50, 50);

Watch out: Colors stay set until changed. push()/pop() restore them.

#noFill()

function2DGame Lab

Draws shapes without filling them (only an outline).

No parameters.

Returns: void

noFill();
stroke("white");
rect(10, 10, 50, 50);

Watch out: Text also uses the fill color: with noFill() text turns black.

#stroke(color)

function2DGame Lab

Sets the outline color.

NameTypeRequiredWhat it is
colorstring|numberyesOutline color

Returns: void

stroke("blue");
strokeWeight(3);
ellipse(200, 200, 80, 80);

Watch out: The outline is invisible when strokeWeight is 0 or after noStroke().

#noStroke()

function2DGame Lab

Turns outlines off.

No parameters.

Returns: void

noStroke();
fill("green");
rect(0, 0, 40, 40);

Watch out: Stroke stays off until stroke() is called again.

#strokeWeight(weight)

function2DGame Lab

Sets the outline thickness.

NameTypeRequiredWhat it is
weightnumberyesOutline thickness in pixels

Returns: void

strokeWeight(4);

Watch out: Also controls line() thickness.

#rect(x, y, width, height?)

function2DGame Lab

Draws a rectangle.

NameTypeRequiredWhat it is
xnumberyesLeft (or center, see rectMode)
ynumberyesTop
widthnumberyesWidth
heightnumberoptionalHeight (default = width)

Returns: void

fill("orange");
rect(100, 100, 80, 40);

Watch out: x,y is the top-left corner unless rectMode(CENTER) was used.

#ellipse(x, y, width, height?)

function2DGame Lab

Draws an ellipse (or circle).

NameTypeRequiredWhat it is
xnumberyesCenter x
ynumberyesCenter y
widthnumberyesWidth
heightnumberoptionalHeight (default = width)

Returns: void

ellipse(200, 200, 100, 60);

Watch out: x,y is the center by default.

#circle(x, y, diameter)

function2DGame Lab

Draws a circle. The third value is the DIAMETER, not the radius.

NameTypeRequiredWhat it is
xnumberyesCenter x
ynumberyesCenter y
diameternumberyesDiameter

Returns: void

circle(200, 200, 50);

Watch out: Diameter, not radius.

#line(x1, y1, x2, y2)

function2DGame Lab

Draws a line.

NameTypeRequiredWhat it is
x1numberyesStart x
y1numberyesStart y
x2numberyesEnd x
y2numberyesEnd y

Returns: void

stroke("white");
line(0, 0, 400, 400);

Watch out: Uses the stroke color; with noStroke() nothing appears.

#point(x, y)

function2DGame Lab

Draws a single point.

NameTypeRequiredWhat it is
xnumberyesx
ynumberyesy

Returns: void

stroke("yellow");
strokeWeight(5);
point(100, 100);

Watch out: Make it visible with strokeWeight().

#triangle(x1, y1, x2, y2, x3, y3)

function2DGame Lab

Draws a triangle from three corners.

NameTypeRequiredWhat it is
x1numberyesx1
y1numberyesy1
x2numberyesx2
y2numberyesy2
x3numberyesx3
y3numberyesy3

Returns: void

triangle(200, 50, 150, 150, 250, 150);

Watch out: Corner order does not matter.

#arc(x, y, width, height, start, stop)

function2DGame Lab

Draws part of an ellipse between two angles (degrees unless angleMode(RADIANS)).

NameTypeRequiredWhat it is
xnumberyesCenter x
ynumberyesCenter y
widthnumberyesWidth
heightnumberyesHeight
startnumberyesStart angle
stopnumberyesStop angle

Returns: void

arc(200, 200, 100, 100, 0, 270);

Watch out: Angles go clockwise starting at 3 o'clock.

#text(value, x, y)

function2DGame Lab

Draws text. Uses the fill color and textSize().

NameTypeRequiredWhat it is
valueanyyesText or number to show
xnumberyesx
ynumberyesy

Returns: void

fill("white");
textSize(20);
text("Score: " + score, 10, 30);

Watch out: Text is drawn with the FILL color. y is the text baseline unless textAlign changes it.

#textSize(size)

function2DGame Lab

Sets the text size.

NameTypeRequiredWhat it is
sizenumberyesFont size in pixels

Returns: void

textSize(24);

Watch out: Stays until changed.

#textAlign(horizontal, vertical?)

function2DGame Lab

Sets how text is positioned around x,y.

NameTypeRequiredWhat it is
horizontalstringyesLEFT, CENTER or RIGHT
verticalstringoptionalTOP, CENTER, BOTTOM or BASELINE

Returns: void

textAlign(CENTER, CENTER);
text("Hello", 200, 200);

Watch out: Use the constants without quotes.

#image(img, x, y, width?, height?)

function2DGame Lab

Draws an image (top-left corner at x,y unless imageMode changed).

NameTypeRequiredWhat it is
imgImage|AnimationyesImage from loadImage()
xnumberyesx
ynumberyesy
widthnumberoptionalDraw width
heightnumberoptionalDraw height

Returns: void

image(bg, 0, 0, 400, 400);

Watch out: Load images once with loadImage(), not every frame.

#imageMode(mode)

function2DGame Lab

Chooses whether image() x,y is the corner or the center.

NameTypeRequiredWhat it is
modestringyesCORNER or CENTER

Returns: void

imageMode(CENTER);

Watch out: Use the constants without quotes.

#rectMode(mode)

function2DGame Lab

Chooses how rect() reads its arguments.

NameTypeRequiredWhat it is
modestringyesCORNER, CENTER, CORNERS or RADIUS

Returns: void

rectMode(CENTER);
rect(200, 200, 50, 50);

Watch out: Stays until changed.

#ellipseMode(mode)

function2DGame Lab

Chooses how ellipse() reads its arguments.

NameTypeRequiredWhat it is
modestringyesCENTER, CORNER, CORNERS or RADIUS

Returns: void

ellipseMode(CORNER);

Watch out: Stays until changed.

#push()

function2DGame Lab

Saves the current drawing style and transform. Pair every push() with a pop().

No parameters.

Returns: void

push();
translate(100, 100);
rect(0, 0, 20, 20);
pop();

Watch out: Forgetting pop() leaves the transform applied.

#pop()

function2DGame Lab

Restores the style and transform saved by push().

No parameters.

Returns: void

pop();

Watch out: Needs a matching push().

#translate(x, y)

function2DGame Lab-style

Moves the drawing origin.

NameTypeRequiredWhat it is
xnumberyesMove right
ynumberyesMove down

Returns: void

translate(200, 200);
rect(0, 0, 40, 40);

Watch out: Affects everything drawn afterwards; wrap in push()/pop().

#rotate(angle)

function2DGame Lab-style

Rotates the drawing (degrees unless angleMode(RADIANS)).

NameTypeRequiredWhat it is
anglenumberyesDegrees

Returns: void

push();
translate(200, 200);
rotate(45);
rect(-20, -20, 40, 40);
pop();

Watch out: Rotation is around the current origin.

#scale(x, y?)

function2DGame Lab-style

Scales the drawing.

NameTypeRequiredWhat it is
xnumberyesHorizontal factor
ynumberoptionalVertical factor (default = x)

Returns: void

push();
scale(2);
rect(10, 10, 20, 20);
pop();

Watch out: Also scales line thickness.

#CENTER

constant2DGame Lab

Constant for centered drawing/alignment.

Type: string

rectMode(CENTER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#CORNER

constant2DGame Lab

Constant: x,y is the top-left corner.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#CORNERS

constant2DGame Lab

Constant: two opposite corners are given.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#RADIUS

constant2DGame Lab

Constant: width and height are radii.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#LEFT

constant2DGame Lab

Constant for left text alignment.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#RIGHT

constant2DGame Lab

Constant for right text alignment.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#TOP

constant2DGame Lab

Constant for top vertical alignment.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#BOTTOM

constant2DGame Lab

Constant for bottom vertical alignment.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#BASELINE

constant2DGame Lab

Constant for baseline vertical alignment (default).

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#DEGREES

constant2DGame Lab

Constant for angleMode(DEGREES), the default.

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#RADIANS

constant2DGame Lab

Constant for angleMode(RADIANS).

Type: string

rectMode(CORNER);

Watch out: Write the constants without quotes (CENTER, not "CENTER").

#PI

constant2D + 3DGame Lab

The number pi (3.14159...).

Type: number

var c = 2 * PI * 10;

Watch out: Use the constant, not 3.14.

#TWO_PI

constant2D + 3DGame Lab

2 * pi.

Type: number

var full = TWO_PI;

Watch out: Angles in Nova default to degrees.

#HALF_PI

constant2D + 3DGame Lab

pi / 2.

Type: number

var q = HALF_PI;

Watch out: See PI.

#QUARTER_PI

constant2D + 3DGame Lab

pi / 4.

Type: number

var q = QUARTER_PI;

Watch out: See PI.

Input 20

#keyDown(key)

function2D + 3DGame Lab

True every frame while the key is held down.

NameTypeRequiredWhat it is
keystringyesKey name such as "left", "LEFT_ARROW", "a", "space", "enter", "shift", "w", "1", "up", "down", "right"

Returns: boolean

if (keyDown("LEFT_ARROW")) { player.x -= 4; }

Watch out: Key names are strings with quotes. Letters are case-insensitive ("a" and "A" are the same key).

#keyWentDown(key)

function2D + 3DGame Lab

True for exactly one frame when the key is pressed.

NameTypeRequiredWhat it is
keystringyesKey name such as "left", "LEFT_ARROW", "a", "space", "enter", "shift", "w", "1", "up", "down", "right"

Returns: boolean

if (keyWentDown("SPACE")) { player.velocityY = -10; }

Watch out: Use it for jumps and shots; keyDown() would repeat every frame.

#keyWentUp(key)

function2D + 3DGame Lab

True for exactly one frame when the key is released.

NameTypeRequiredWhat it is
keystringyesKey name such as "left", "LEFT_ARROW", "a", "space", "enter", "shift", "w", "1", "up", "down", "right"

Returns: boolean

if (keyWentUp("SPACE")) { print("released"); }

Watch out: Only one frame long.

#mouseDown(button?)

function2D + 3DGame Lab

True while the mouse button is held.

NameTypeRequiredWhat it is
buttonstringoptional"left" (default), "right" or "middle"

Returns: boolean

if (mouseDown("left")) { ball.x = mouseX; }

Watch out: Use quotes: "left".

#mouseWentDown(button?)

function2D + 3DGame Lab

True for one frame when the button is pressed.

NameTypeRequiredWhat it is
buttonstringoptional"left" (default), "right" or "middle"

Returns: boolean

if (mouseWentDown("left")) { createSprite(mouseX, mouseY, 10, 10); }

Watch out: One frame only.

#mouseWentUp(button?)

function2D + 3DGame Lab

True for one frame when the button is released.

NameTypeRequiredWhat it is
buttonstringoptional"left" (default), "right" or "middle"

Returns: boolean

if (mouseWentUp("left")) { print("up"); }

Watch out: One frame only.

#mouseIsPressed()

function2D + 3DGame Lab

True while any mouse button is held.

No parameters.

Returns: boolean

if (mouseIsPressed()) { background("red"); }

Watch out: It is a function here: call it with ().

#mouseIsOver(sprite)

function2DGame Lab

True if the mouse pointer is over the sprite.

NameTypeRequiredWhat it is
spriteSprite|NodeyesSprite or scene node (getNode) to test

Returns: boolean

if (mouseIsOver(button)) { button.shapeColor = "yellow"; }

Watch out: Uses the sprite collider; with the camera on it uses world coordinates.

#mousePressedOver(sprite)

function2DGame Lab

True for the one frame in which the left button is pressed while the pointer is over the sprite.

NameTypeRequiredWhat it is
spriteSprite|NodeyesSprite or scene node (getNode) to test

Returns: boolean

if (mousePressedOver(button)) { score++; }

Watch out: One frame only: it is a click, not a hold.

#mouseX

object2D + 3DGame Lab

Current mouse x in screen coordinates. Updated every frame.

Type: number read-only

player.x = mouseX;

Watch out: Screen coordinates ignore the camera; use camera.mouseX for the world position.

#mouseY

object2D + 3DGame Lab

Current mouse y in screen coordinates.

Type: number read-only

player.y = mouseY;

Watch out: See mouseX.

#pmouseX

object2D + 3DGame Lab

Mouse x in the previous frame.

Type: number read-only

var dx = mouseX - pmouseX;

Watch out: Equals mouseX on the first frame.

#pmouseY

object2D + 3DGame Lab

Mouse y in the previous frame.

Type: number read-only

var dy = mouseY - pmouseY;

Watch out: See pmouseX.

#mouseDeltaX()

function2D + 3DVYOM

How far the mouse moved horizontally since the last frame. Works while the mouse is captured, which makes it the right tool for mouse-look in 3D.

No parameters.

Returns: number

rotate3D(0, -mouseDeltaX() * 0.1, 0);

Watch out: Call captureMouse(true) first for first-person controls.

#mouseDeltaY()

function2D + 3DVYOM

How far the mouse moved vertically since the last frame.

No parameters.

Returns: number

var tilt = mouseDeltaY() * 0.1;

Watch out: See mouseDeltaX.

#captureMouse(on?)

function2D + 3DVYOM

Locks and hides the mouse pointer so you can read unlimited mouse movement with mouseDeltaX()/mouseDeltaY() (first-person look). Pass false to release it.

NameTypeRequiredWhat it is
onbooleanoptionaltrue to hide and lock the pointer (default true)

Returns: void

function start() {
  captureMouse(true);
}

Watch out: The player cannot click anything else while it is captured. Release it for menus.

#mouseDidMove()

function2D + 3DGame Lab

True if the mouse pointer moved since the previous frame.

No parameters.

Returns: boolean

if (mouseDidMove()) { hint.visible = false; }

Watch out: It is a function: call it with ().

#anyKeyDown()

function2D + 3DVYOM

True while any keyboard key is held.

No parameters.

Returns: boolean

if (anyKeyDown()) { print("typing"); }

Watch out: Mouse buttons are not keys.

#anyKeyWentDown()

function2D + 3DVYOM

True for one frame when any key is pressed (perfect for "Press any key to start").

No parameters.

Returns: boolean

if (anyKeyWentDown()) { gameState = "play"; }

Watch out: One frame only.

#getSpriteAt(x, y)

function2DVYOM

Returns the front-most visible sprite under a point, or undefined. Use it to find what was clicked.

NameTypeRequiredWhat it is
xnumberyesx position
ynumberyesy position

Returns: Sprite

if (mouseWentDown()) {
  var s = getSpriteAt(mouseX, mouseY);
  if (s) { s.destroy(); }
}

Watch out: Uses the collider; check the result before using it (it can be undefined).

Math & random 33

#random(a?, b?)

function2D + 3DGame Lab-style

random() gives 0 up to 1, random(max) 0 up to max, random(min, max) between them. With an array it returns a random element. Decimals are possible.

NameTypeRequiredWhat it is
anumber|ArrayoptionalMax, or min; or an array to pick from
bnumberoptionalMax when a is the min

Returns: number

var x = random(0, 400);
var c = random(["red", "green", "blue"]);

Watch out: random(1, 6) does NOT return whole numbers; use randomNumber(1, 6) for dice.

#randomNumber(min, max)

function2D + 3DGame Lab

Random WHOLE number from min to max, both included. (Game Lab's main random function.)

NameTypeRequiredWhat it is
minnumberyesLowest whole number
maxnumberyesHighest whole number

Returns: number

var dice = randomNumber(1, 6);

Watch out: Both ends can be returned.

#randomChoice(array)

function2D + 3DVYOM

Returns a random element of an array.

NameTypeRequiredWhat it is
arrayArrayyesArray to pick from

Returns: any

var enemyColor = randomChoice(["red", "blue"]);

Watch out: The array must not be empty.

#rgb(r, g, b)

function2D + 3DGame Lab

Makes a color string.

NameTypeRequiredWhat it is
rnumberyes0-255
gnumberyes0-255
bnumberyes0-255

Returns: string

fill(rgb(255, 128, 0));

Watch out: Returns a string like "rgb(255,128,0)".

#rgba(r, g, b, a)

function2D + 3DGame Lab

Makes a color string with opacity.

NameTypeRequiredWhat it is
rnumberyes0-255
gnumberyes0-255
bnumberyes0-255
anumberyes0-1 opacity

Returns: string

fill(rgba(255, 0, 0, 0.5));

Watch out: Alpha is 0 to 1, not 0 to 255.

#map(value, start1, stop1, start2, stop2)

function2D + 3DGame Lab

Re-maps a number from one range to another.

NameTypeRequiredWhat it is
valuenumberyesValue to convert
start1numberyesInput range start
stop1numberyesInput range end
start2numberyesOutput range start
stop2numberyesOutput range end

Returns: number

var x = map(mouseX, 0, 400, 0, 100);

Watch out: The result is not limited to the output range; combine with constrain().

#dist(x1, y1, x2, y2)

function2D + 3DGame Lab

Distance between two points.

NameTypeRequiredWhat it is
x1numberyesx1
y1numberyesy1
x2numberyesx2
y2numberyesy2

Returns: number

if (dist(player.x, player.y, enemy.x, enemy.y) < 50) { alert1(); }

Watch out: Four numbers, not two sprites.

#constrain(value, low, high)

function2D + 3DGame Lab

Keeps a number between low and high.

NameTypeRequiredWhat it is
valuenumberyesValue
lownumberyesMinimum
highnumberyesMaximum

Returns: number

player.x = constrain(player.x, 20, 380);

Watch out: Order is (value, low, high).

#lerp(a, b, t)

function2D + 3DGame Lab

Linear interpolation between a and b.

NameTypeRequiredWhat it is
anumberyesStart
bnumberyesEnd
tnumberyes0 to 1

Returns: number

camera.x = lerp(camera.x, player.x, 0.1);

Watch out: t = 0 gives a, t = 1 gives b.

#round(value)

function2D + 3DGame Lab

Rounds to the nearest whole number.

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var n = round(2.6);

Watch out: Halves round up.

#floor(value)

function2D + 3DGame Lab

Rounds down.

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var n = floor(2.9);

Watch out: Negative numbers round toward minus infinity.

#ceil(value)

function2D + 3DGame Lab

Rounds up.

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var n = ceil(2.1);

Watch out: Negative numbers round toward zero.

#abs(value)

function2D + 3DGame Lab

Absolute value (without the minus sign).

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var d = abs(a - b);

Watch out: Never negative.

#sqrt(value)

function2D + 3DGame Lab

Square root.

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var r = sqrt(16);

Watch out: NaN for negative numbers.

#pow(base, exponent)

function2D + 3DGame Lab

base to the power of exponent.

NameTypeRequiredWhat it is
basenumberyesBase
exponentnumberyesExponent

Returns: number

var s = pow(2, 8);

Watch out: Order is (base, exponent).

#sin(angle)

function2D + 3DGame Lab

Sine of an angle. Angles are in degrees by default like in Game Lab.

NameTypeRequiredWhat it is
anglenumberyesDegrees (RADIANS after angleMode(RADIANS))

Returns: number

var h = sin(30);

Watch out: JavaScript's Math.sin uses radians; this one uses degrees.

#cos(angle)

function2D + 3DGame Lab

Cosine of an angle in degrees.

NameTypeRequiredWhat it is
anglenumberyesDegrees

Returns: number

var w = cos(60);

Watch out: Degrees by default.

#tan(angle)

function2D + 3DGame Lab

Tangent of an angle in degrees.

NameTypeRequiredWhat it is
anglenumberyesDegrees

Returns: number

var t = tan(45);

Watch out: Degrees by default.

#asin(value)

function2D + 3DGame Lab

Arc sine, returned in degrees.

NameTypeRequiredWhat it is
valuenumberyes-1 to 1

Returns: number

var a = asin(0.5);

Watch out: Result unit follows angleMode.

#acos(value)

function2D + 3DGame Lab

Arc cosine, returned in degrees.

NameTypeRequiredWhat it is
valuenumberyes-1 to 1

Returns: number

var a = acos(0.5);

Watch out: Result unit follows angleMode.

#atan(value)

function2D + 3DGame Lab

Arc tangent, returned in degrees.

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var a = atan(1);

Watch out: Use atan2 for directions.

#atan2(y, x)

function2D + 3DGame Lab

Angle of the vector (x, y) in degrees. Note that y comes first.

NameTypeRequiredWhat it is
ynumberyesy difference
xnumberyesx difference

Returns: number

var angle = atan2(mouseY - player.y, mouseX - player.x);

Watch out: The order is (y, x).

#degrees(radians)

function2D + 3DGame Lab

Converts radians to degrees.

NameTypeRequiredWhat it is
radiansnumberyesAngle in radians

Returns: number

var d = degrees(PI);

Watch out: Not affected by angleMode.

#radians(degrees)

function2D + 3DGame Lab

Converts degrees to radians.

NameTypeRequiredWhat it is
degreesnumberyesAngle in degrees

Returns: number

var r = radians(180);

Watch out: Not affected by angleMode.

#min(values...)

function2D + 3DGame Lab

Smallest of the numbers.

NameTypeRequiredWhat it is
values...numberyesNumbers

Returns: number

var m = min(a, b, c);

Watch out: With an empty call the result is Infinity.

#max(values...)

function2D + 3DGame Lab

Largest of the numbers.

NameTypeRequiredWhat it is
values...numberyesNumbers

Returns: number

var m = max(a, b, c);

Watch out: With an empty call the result is -Infinity.

#sq(value)

function2D + 3DGame Lab

Square of a number.

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var a = sq(5);

Watch out: Same as value * value.

#log(value)

function2D + 3DGame Lab

Natural logarithm.

NameTypeRequiredWhat it is
valuenumberyesNumber

Returns: number

var l = log(10);

Watch out: Natural log (base e), not base 10.

#exp(value)

function2D + 3DGame Lab

e raised to the power.

NameTypeRequiredWhat it is
valuenumberyesExponent

Returns: number

var e1 = exp(1);

Watch out: e is about 2.718.

#mag(x, y)

function2D + 3DGame Lab

Length of the vector (x, y).

NameTypeRequiredWhat it is
xnumberyesx
ynumberyesy

Returns: number

var speed = mag(vx, vy);

Watch out: Two numbers.

#norm(value, start, stop)

function2D + 3DGame Lab

Converts a value in a range to 0..1.

NameTypeRequiredWhat it is
valuenumberyesValue
startnumberyesRange start
stopnumberyesRange end

Returns: number

var t = norm(mouseX, 0, 400);

Watch out: Not limited to 0..1.

#angleMode(mode)

function2D + 3DGame Lab

Chooses whether sin/cos/tan/rotate use degrees (default) or radians.

NameTypeRequiredWhat it is
modestringyesDEGREES or RADIANS

Returns: void

angleMode(RADIANS);

Watch out: Affects all angle functions from then on.

#shuffle(array)

function2D + 3DVYOM

Returns a new array with the same items in random order (the original is not changed).

NameTypeRequiredWhat it is
arrayArrayyesArray to shuffle

Returns: Array

var order = shuffle([1, 2, 3, 4]);

Watch out: It returns a copy: use the result.

Scene nodes 9

#getNode(path)

function2D + 3DVYOM

Finds a node in the running scene by path and returns a reference (NodeRef). Returns a Node2DRef or Node3DRef automatically when the node is a 2D or 3D node.

NameTypeRequiredWhat it is
pathstringyesNode path relative to the root of the running scene, e.g. "Player" or "World/Enemies/Boss"

Returns: NodeRef – Reference to the node, or null

var door = getNode("World/Door");
if (door) { door.visible = false; }

Watch out: The path starts at the root node of the scene, without the root's own name. Returns null (with a warning) if no node is found.

#findNode(name)

function2D + 3DVYOM

Searches the whole scene tree for a node with this name.

NameTypeRequiredWhat it is
namestringyesNode name

Returns: NodeRef – First node with this name, or null

var boss = findNode("Boss");

Watch out: Names are case sensitive. If several nodes share a name the first one found is returned.

#getNodesInGroup(group)

function2D + 3DVYOM

Returns all nodes that belong to a Godot group.

NameTypeRequiredWhat it is
groupstringyesGroup name set in the Scene dock / Inspector

Returns: NodeRef[] – Array of nodes

var enemies = getNodesInGroup("enemies");
for (var i = 0; i < enemies.length; i++) { enemies[i].destroy(); }

Watch out: Groups are added in the Scene dock (Groups button) or with node.addToGroup(). An unknown group returns an empty array.

#getNode3D(path)

function3DVYOM

Like getNode() but guarantees a 3D reference with position/rotation/scale and 3D movement methods.

NameTypeRequiredWhat it is
pathstringyesNode path

Returns: Node3DRef – Reference or null

var player = getNode3D("Player");
player.position = vec3(0, 2, 0);

Watch out: Use getNode() for 2D nodes.

#findNode3D(name)

function3DVYOM

Searches the scene for a 3D node by name.

NameTypeRequiredWhat it is
namestringyesNode name

Returns: Node3DRef – Reference or null

var cam = findNode3D("Camera3D");

Watch out: Returns null if the node is not a Node3D.

#createObject3D(type, x?, y?, z?)

function3DVYOM

Creates a new 3D object at run time and adds it to the scene. Boxes, spheres, capsules, cylinders and planes become a visible mesh; "light" becomes an OmniLight3D; "camera" a Camera3D.

NameTypeRequiredWhat it is
typestringyes"box", "sphere", "capsule", "cylinder", "plane", "light" or "camera"
xnumberoptionalX position
ynumberoptionalY position
znumberoptionalZ position

Returns: Node3DRef – The new object

var crate = createObject3D("box", 0, 1, -5);
crate.scale = vec3(2, 2, 2);

Watch out: The created meshes have no collision. For solid objects build them in the editor with a StaticBody3D + CollisionShape3D, or load a scene with spawn3D().

#spawn3D(scene, position?)

function3DVYOM

Instances a scene (as made in the editor) into the running game and places it. The scene's own script, if any, runs.

NameTypeRequiredWhat it is
scenestringyesPath of a .tscn scene, e.g. "res://scenes/enemy.tscn"
positionVec3|number[]optionalWhere to put it (default 0,0,0)

Returns: Node3DRef – The new instance

var enemy = spawn3D("res://scenes/enemy.tscn", vec3(5, 0, -10));

Watch out: The path must exist in the project. Spawn at run time, not every frame.

#destroy3D(node)

function3DVYOM

Removes a node (and its children) from the running scene.

NameTypeRequiredWhat it is
nodeNodeRefyesNode to remove

Returns: void

destroy3D(enemy);

Watch out: Do not use a node after destroying it. node.isValid() tells you if it still exists.

#raycast3D(origin, direction, distance?)

function3DVYOM

Casts a ray through the physics world and reports the first collider it hits.

NameTypeRequiredWhat it is
originVec3yesStart point
directionVec3yesDirection (does not need to be normalized)
distancenumberoptionalMaximum length (default 1000)

Returns: object|null – {hit, position, normal, distance, collider} or null when nothing was hit

var hit = raycast3D(camera3D.position, vec3(0, 0, -1), 50);
if (hit) { print("Hit " + hit.collider.name + " at " + hit.distance); }

Watch out: Only physics bodies/areas on the ray are hit. Inside a script attached to a node the ray automatically ignores that node itself (so a player does not hit its own collision shape).

Node references 42

#node.path

property2D + 3DVYOM

Path of the node in the scene.

Type: string

print(boss.path);

Watch out: Read-only.

#node.name

property2D + 3DVYOM

Name of the node.

Type: string

print(boss.name);

Watch out: Read-only; rename in the editor.

#node.type

property2D + 3DVYOM

Godot class of the node, e.g. "CharacterBody3D".

Type: string

if (n.type === "Area3D") { }

Watch out: Read-only.

#node.visible

property2D + 3DVYOM

Shows or hides the node (and children).

Type: boolean

ghost.visible = false;

Watch out: Hidden physics bodies still collide.

#node.isValid()

method2D + 3DVYOM

True if the node still exists (was not destroyed).

No parameters.

Returns: boolean

if (target.isValid()) { target.visible = true; }

Watch out: Use before touching nodes other scripts may destroy.

#node.getProperty(name)

method2D + 3DVYOM

Reads any Godot property of the node, e.g. "modulate" or "mass".

NameTypeRequiredWhat it is
namestringyesGodot property name

Returns: any

var m = crate.getProperty("mass");

Watch out: Property names are Godot's (snake_case): "collision_layer".

#node.setProperty(name, value)

method2D + 3DVYOM

Sets any Godot property of the node. Numbers, strings, booleans, arrays [x,y] / [x,y,z] and {r,g,b,a} objects are converted to Godot types.

NameTypeRequiredWhat it is
namestringyesGodot property name
valueanyyesNew value

Returns: void

crate.setProperty("mass", 5);

Watch out: Wrong names are reported as warnings in the Output.

#node.call(method, args...)

method2D + 3DVYOM

Calls a Godot method on the node.

NameTypeRequiredWhat it is
methodstringyesGodot method name
args...anyyesArguments

Returns: any

player.call("play", "walk");

Watch out: Use Godot's method names (snake_case).

#node.destroy()

method2D + 3DVYOM

Removes the node from the scene.

No parameters.

Returns: void

coin.destroy();

Watch out: The reference becomes invalid.

#node.remove()

method2D + 3DVYOM

Same as destroy().

No parameters.

Returns: void

coin.remove();

Watch out: See destroy.

#node.getParent()

method2D + 3DVYOM

Returns the parent node.

No parameters.

Returns: NodeRef

var p = child.getParent();

Watch out: Returns null for the root.

#node.getChildren()

method2D + 3DVYOM

Returns the child nodes.

No parameters.

Returns: NodeRef[]

var kids = enemies.getChildren();

Watch out: Direct children only.

#node.findChild(name)

method2D + 3DVYOM

Searches the descendants for a node by name.

NameTypeRequiredWhat it is
namestringyesChild name

Returns: NodeRef

var gun = player.findChild("Gun");

Watch out: Returns null if there is none.

#node.isInGroup(group)

method2D + 3DVYOM

True if the node is in the group.

NameTypeRequiredWhat it is
groupstringyesGroup name

Returns: boolean

if (other.isInGroup("enemies")) { }

Watch out: Group names are case sensitive.

#node.addToGroup(group)

method2D + 3DVYOM

Adds the node to a group.

NameTypeRequiredWhat it is
groupstringyesGroup name

Returns: void

crate.addToGroup("pickups");

Watch out: Groups added at run time are not saved to the scene.

#node.equals(other)

method2D + 3DVYOM

True if both references point to the same node.

NameTypeRequiredWhat it is
otherNodeRefyesOther reference

Returns: boolean

if (other.equals(player)) { }

Watch out: Use it instead of === (two references to one node are different objects).

#node.x

property2DVYOM

Horizontal position (2D).

Type: number

node.x += 2;

Watch out: Y points down.

#node.y

property2DVYOM

Vertical position (2D).

Type: number

node.y += 2;

Watch out: Y points down.

#node.position

property2DVYOM

Position as {x, y} (2D).

Type: object

node.position = {x: 10, y: 20};

Watch out: Assign a whole object to change it.

#node.rotation

property2DVYOM

Rotation in degrees (2D).

Type: number

node.rotation = 90;

Watch out: Degrees, not radians.

#node.scaleX

property2DVYOM

Horizontal scale (2D).

Type: number

node.scaleX = 2;

Watch out: 1 is normal.

#node.scaleY

property2DVYOM

Vertical scale (2D).

Type: number

node.scaleY = 2;

Watch out: 1 is normal.

#node.setScale(x, y?)

method2DVYOM

Sets both scale components.

NameTypeRequiredWhat it is
xnumberyesHorizontal scale
ynumberoptionalVertical scale (default = x)

Returns: void

node.setScale(2);

Watch out: 1 is normal size.

#node.zIndex

property2DVYOM

Draw order (2D). A node with a higher zIndex is drawn in front of nodes with a lower one. It is added to the parent's zIndex, so a child with zIndex = 1 is drawn in front of its parent's pictures.

Type: number

var heldCoin = getNode("heldCoin");
heldCoin.zIndex = 1;   // show the held coin in front of the player

Watch out: With the same zIndex the node lower in the scene tree is in front, so a child listed above its parent's Sprite2D is drawn behind it.

#node.velocityX

property2D + 3DVYOM

Horizontal speed of a scene node. In 2D it is pixels per FRAME, just like sprites (the engine moves the node for you every frame; a CharacterBody2D stops at walls, a RigidBody2D gets a physics speed). In 3D it is metres per second of a CharacterBody3D / RigidBody3D.

Type: number

var player = getNode("character");
function update() {
  player.velocityX = 4;   // moves right every frame
}

Watch out: Set it once to keep moving; set it back to 0 to stop. 2D: per frame. 3D: per second, and a CharacterBody3D also needs moveAndSlide3D() each frame.

#node.velocityY

property2D + 3DVYOM

Vertical speed of a scene node. 2D: pixels per frame, positive moves DOWN (a jump needs a negative value). 3D: metres per second, positive moves UP.

Type: number

player.velocityY = -6;   // up on the 2D screen

Watch out: Same units as velocityX. In 2D y points down, in 3D y points up.

#Node3D.velocityZ

property3DVYOM

Depth speed of a 3D scene node (CharacterBody3D / RigidBody3D) in metres per second. Negative is forward.

Type: number

player.velocityZ = -5;   // walk forward

Watch out: Only 3D nodes have z. A CharacterBody3D also needs moveAndSlide3D() each frame to actually move.

#node.setVelocity(vx, vy, vz?)

method2D + 3DVYOM

Sets the speed of a scene node at once: x and y for 2D (pixels per frame), x, y and z for 3D (metres per second).

NameTypeRequiredWhat it is
vxnumberyesHorizontal speed
vynumberyesVertical speed
vznumberoptionalDepth speed (3D only)

Returns: void

player.setVelocity(4, 0);

Watch out: Same units as velocityX / velocityY / velocityZ.

#node.isTouching(target)

method2DVYOM

True if this scene node touches or overlaps the target. The box used is the node's collision shapes (CollisionShape2D); a node without any uses its sprite picture.

NameTypeRequiredWhat it is
targetNodeRef|Sprite|GroupyesA node from getNode(), a sprite, or a group / array of them

Returns: boolean

var player = getNode("player");
var coin = getNode("Coin");
function update() {
  if (player.isTouching(coin)) { coin.visible = false; }
}

Watch out: It only tells you; it does not stop movement. For scene nodes use it instead of collide()/bounce(), which are for sprites. Call getNode() once at the top, not every frame.

#node.isColliding(target)

method2DVYOM

Same as isTouching().

NameTypeRequiredWhat it is
targetNodeRef|Sprite|GroupyesTarget

Returns: boolean

if (player.isColliding(spike)) { print("ouch"); }

Watch out: See isTouching.

#node.isOverlapping(target)

method2DVYOM

True only if the boxes really overlap (just touching edges does not count).

NameTypeRequiredWhat it is
targetNodeRef|Sprite|GroupyesTarget

Returns: boolean

if (player.isOverlapping(zone)) { print("inside"); }

Watch out: See isTouching.

#node.touched(target)

method2DVYOM

True when this node HAS touched the target before and is NOT touching it right now. isTouching() is only true while they touch; touched() becomes true when they separate and stays true afterwards (false again while they touch).

NameTypeRequiredWhat it is
targetNodeRef|Sprite|GroupyesTarget

Returns: boolean

var player = getNode("player");
var coin = getNode("Coin");
function draw() {
  if (player.touched(coin)) {
    print("the player already visited the coin");
  }
}

Watch out: Call it every frame (for example in draw()): it starts watching the pair the first time you call it, so contact before that first call does not count. Hiding a node does not change this.

#node.mouseIsOver()

method2DVYOM

True while the mouse pointer is over this scene node.

No parameters.

Returns: boolean

if (button.mouseIsOver()) { button.visible = true; }

Watch out: Uses the same box as isTouching().

#node.mousePressedOver()

method2DVYOM

True for the one frame in which the left mouse button is clicked over this node.

No parameters.

Returns: boolean

if (playButton.mousePressedOver()) { print("start"); }

Watch out: One frame per click.

#node.mouseHeldOver()

method2DVYOM

True every frame while the left mouse button is held down over this node.

No parameters.

Returns: boolean

if (slider.mouseHeldOver()) { slider.x = mouseX; }

Watch out: See mousePressedOver.

#node.mouseReleasedOver()

method2DVYOM

True for the one frame in which the left mouse button is released over this node.

No parameters.

Returns: boolean

if (card.mouseReleasedOver()) { print("dropped"); }

Watch out: One frame only.

#node.distanceTo(x_or_target, y?)

method2DVYOM

Distance in pixels from this node to a point, node or sprite.

NameTypeRequiredWhat it is
x_or_targetnumber|NodeRef|SpriteyesA number (then pass y too), a node or a sprite
ynumberoptionaly when the first argument is a number

Returns: number

if (enemy.distanceTo(player) < 100) { print("close"); }

Watch out: Uses the nodes' positions (x, y).

#node.angleTo(x_or_target, y?)

method2DVYOM

Direction in degrees from this node to a point or node (0 = right, 90 = down).

NameTypeRequiredWhat it is
x_or_targetnumber|NodeRef|SpriteyesA number (then pass y too), a node or a sprite
ynumberoptionaly when the first argument is a number

Returns: number

enemy.rotation = enemy.angleTo(player);

Watch out: Degrees; 90 points DOWN.

#node.moveTowards(x_or_target, y_or_speed, speed?)

method2DVYOM

Moves the node straight towards a point or node by at most speed pixels, never overshooting. Returns true when it arrived.

NameTypeRequiredWhat it is
x_or_targetnumber|NodeRef|SpriteyesA number (then pass y and speed), a node or a sprite (then pass speed)
y_or_speednumberyesy, or the speed when the first argument is a node
speednumberoptionalPixels to move this frame

Returns: boolean

function update() {
  enemy.moveTowards(player, 2);
}

Watch out: Call it every frame in update(). It sets the position directly (no physics).

#node.setPosition(x, y)

method2DVYOM

Puts the node at x, y.

NameTypeRequiredWhat it is
xnumberyesNew x
ynumberyesNew y

Returns: Node2D

player.setPosition(100, 200);

Watch out: Same as setting x and y.

#node.hide()

method2DVYOM

Hides the node (visible = false).

No parameters.

Returns: Node2D

coin.hide();

Watch out: Hidden physics bodies still collide.

#node.show()

method2DVYOM

Shows the node again.

No parameters.

Returns: Node2D

coin.show();

Watch out: Opposite of hide().

Vectors 15

#vec3(x?, y?, z?)

function3DVYOM

Creates a 3D vector. Also accepts an array [x, y, z] or another vector.

NameTypeRequiredWhat it is
xnumberoptionalX (default 0)
ynumberoptionalY (default 0)
znumberoptionalZ (default 0)

Returns: Vec3 – A new vector

var up = vec3(0, 1, 0);

Watch out: Y is UP in 3D (Godot convention). -Z is forward.

#v.x

property3DVYOM

X component.

Type: number

v.x = 5;

Watch out: Positive x is right.

#v.y

property3DVYOM

Y component.

Type: number

v.y = 5;

Watch out: Positive y is up.

#v.z

property3DVYOM

Z component.

Type: number

v.z = -5;

Watch out: Negative z is forward (away from the default camera).

#v.add(v)

method3DVYOM

Returns this + v. Does not change this vector.

NameTypeRequiredWhat it is
vVec3yesOther vector

Returns: Vec3

var p = a.add(b);

Watch out: Returns a NEW vector; a is unchanged.

#v.sub(v)

method3DVYOM

Returns this - v.

NameTypeRequiredWhat it is
vVec3yesOther vector

Returns: Vec3

var d = target.sub(me);

Watch out: Returns a new vector.

#v.scale(s)

method3DVYOM

Returns this multiplied by a number.

NameTypeRequiredWhat it is
snumberyesFactor

Returns: Vec3

var big = v.scale(2);

Watch out: Returns a new vector.

#v.length()

method3DVYOM

Length of the vector.

No parameters.

Returns: number

var d = v.length();

Watch out: It is a method: call it with ().

#v.normalize()

method3DVYOM

Returns the vector with length 1 (or zero vector if it was zero).

No parameters.

Returns: Vec3

var dir = d.normalize();

Watch out: Returns a new vector.

#v.dot(v)

method3DVYOM

Dot product.

NameTypeRequiredWhat it is
vVec3yesOther vector

Returns: number

var facing = forward.dot(toEnemy);

Watch out: Result is a number, not a vector.

#v.cross(v)

method3DVYOM

Cross product.

NameTypeRequiredWhat it is
vVec3yesOther vector

Returns: Vec3

var side = forward.cross(up);

Watch out: Order matters (a x b = -(b x a)).

#v.distanceTo(v)

method3DVYOM

Distance to another point.

NameTypeRequiredWhat it is
vVec3yesOther point

Returns: number

if (me.distanceTo(enemy) < 5) { flee(); }

Watch out: Both must be Vec3s.

#v.lerp(v, t)

method3DVYOM

Linear interpolation towards v.

NameTypeRequiredWhat it is
vVec3yesTarget
tnumberyes0 to 1

Returns: Vec3

var p = a.lerp(b, 0.5);

Watch out: t = 0 returns this, t = 1 returns v.

#v.toArray()

method3DVYOM

Returns [x, y, z].

No parameters.

Returns: number[]

var arr = v.toArray();

Watch out: Copy, not a reference.

#v.clone()

method3DVYOM

Returns a copy.

No parameters.

Returns: Vec3

var c = v.clone();

Watch out: Assigning a vector to another variable shares the same object; clone() copies.

3D movement & transforms 43

#self

object3DVYOM

The node this script is attached to.

Type: Node3DRef

self.position = vec3(0, 1, 0);

Watch out: Available in scripts attached to a node.

#move3D(x, y?, z?)

function3DVYOM

Moves the node by an offset in its OWN axes (forward is -Z). The offset is per SECOND and is multiplied by dt automatically, so it behaves the same at any frame rate.

NameTypeRequiredWhat it is
xnumber|Vec3yesX or a vector
ynumberoptionalY
znumberoptionalZ

Returns: void

function update(dt) {
  if (keyDown("w")) { move3D(0, 0, -5); }
}

Watch out: Do not multiply by dt yourself. For solid movement use a CharacterBody3D and moveAndSlide3D().

#rotate3D(x, y?, z?)

function3DVYOM

Rotates the node (degrees per second, multiplied by dt).

NameTypeRequiredWhat it is
xnumber|Vec3yesDegrees around X
ynumberoptionalDegrees around Y
znumberoptionalDegrees around Z

Returns: void

rotate3D(0, 90, 0); // spin once per 4 seconds

Watch out: Degrees per second, not per frame.

#lookAt3D(target)

function3DVYOM

Turns the node so its -Z axis points at the target.

NameTypeRequiredWhat it is
targetVec3|NodeRefyesPoint or node to face

Returns: void

lookAt3D(getNode3D("Player").position);

Watch out: The node must not be exactly above/below the target.

#getPosition3D()

function3DVYOM

Returns the global position.

No parameters.

Returns: Vec3

var p = getPosition3D();

Watch out: A copy: change it with setPosition3D().

#setPosition3D(x, y?, z?)

function3DVYOM

Sets the global position.

NameTypeRequiredWhat it is
xnumber|Vec3yesX or a vector
ynumberoptionalY
znumberoptionalZ

Returns: void

setPosition3D(0, 5, 0);

Watch out: Teleports; physics bodies keep their velocity.

#getRotation3D()

function3DVYOM

Returns the rotation in degrees (x, y, z).

No parameters.

Returns: Vec3

var r = getRotation3D();

Watch out: Degrees, not radians.

#setRotation3D(x, y?, z?)

function3DVYOM

Sets the rotation in degrees.

NameTypeRequiredWhat it is
xnumber|Vec3yesDegrees X or a vector
ynumberoptionalDegrees Y
znumberoptionalDegrees Z

Returns: void

setRotation3D(0, 90, 0);

Watch out: Degrees.

#setScale3D(x, y?, z?)

function3DVYOM

Sets the scale.

NameTypeRequiredWhat it is
xnumber|Vec3yesX or a vector (one number scales all axes)
ynumberoptionalY
znumberoptionalZ

Returns: void

setScale3D(2);

Watch out: Scaling a physics body also scales its collision shape.

#setVelocity3D(x, y?, z?)

function3DVYOM

Sets the velocity of a CharacterBody3D (metres per second).

NameTypeRequiredWhat it is
xnumber|Vec3yesX or a vector
ynumberoptionalY
znumberoptionalZ

Returns: void

setVelocity3D(0, 8, 0); // jump

Watch out: Only CharacterBody3D / RigidBody3D have a velocity.

#moveAndSlide3D()

function3DVYOM

Moves a CharacterBody3D with its current velocity, sliding along walls and floors. Returns true if it collided.

No parameters.

Returns: boolean

function update(dt) {
  velocity3D.y -= gravity3D * dt;
  moveAndSlide3D();
}

Watch out: Only works on CharacterBody3D. Gravity is not automatic: apply it yourself.

#isOnFloor3D()

function3DVYOM

True if the CharacterBody3D stands on the floor (valid after moveAndSlide3D()).

No parameters.

Returns: boolean

if (isOnFloor3D() && keyWentDown("space")) { velocity3D.y = 6; }

Watch out: Call moveAndSlide3D() first, otherwise the value is from the previous frame.

#isColliding3D()

function3DVYOM

True if the body collided during the last moveAndSlide3D().

No parameters.

Returns: boolean

if (isColliding3D()) { print("bump"); }

Watch out: Needs moveAndSlide3D().

#playAnimation3D(name)

function3DVYOM

Plays an animation of the first AnimationPlayer found in the node (e.g. from an imported model).

NameTypeRequiredWhat it is
namestringyesAnimation name from the node's AnimationPlayer

Returns: void

playAnimation3D("run");

Watch out: The animation must exist in the AnimationPlayer; check the Animation panel.

#stopAnimation3D()

function3DVYOM

Stops the current animation.

No parameters.

Returns: void

stopAnimation3D();

Watch out: No-op if nothing plays.

#velocity3D

object3DVYOM

Velocity of the CharacterBody3D this script is attached to. Assign a Vec3 or change .x/.y/.z; used by moveAndSlide3D().

Type: Vec3

velocity3D.x = 4;

Watch out: Metres per second. Gravity is not added automatically.

#gravity3D

object3DVYOM

The project's 3D gravity (default 9.8).

Type: number

velocity3D.y -= gravity3D * dt;

Watch out: Read-only.

#node.position

property3DVYOM

Global position of the referenced node. Assign a vec3() or array to move it.

Type: Vec3

enemy.position = vec3(0, 0, 0);

Watch out: Reading gives a copy: enemy.position.x = 5 changes only the copy; assign the whole vector.

#node.rotation

property3DVYOM

Rotation in degrees.

Type: Vec3

enemy.rotation = vec3(0, 90, 0);

Watch out: Degrees.

#node.scale

property3DVYOM

Scale.

Type: Vec3

enemy.scale = vec3(2, 2, 2);

Watch out: 1 is normal.

#node.velocity

property3DVYOM

Velocity of a CharacterBody3D / RigidBody3D.

Type: Vec3

enemy.velocity = vec3(0, 5, 0);

Watch out: Metres per second.

#node.getVelocity3D()

method3DVYOM

Returns the velocity.

No parameters.

Returns: Vec3

var v = enemy.getVelocity3D();

Watch out: A copy.

#node.move3D(x, y?, z?)

method3DVYOM

Moves the referenced node (see move3D).

NameTypeRequiredWhat it is
xnumber|Vec3yesX or vector
ynumberoptional
znumberoptional

Returns: void

enemy.move3D(0, 0, -3);

Watch out: Per second.

#node.rotate3D(x, y?, z?)

method3DVYOM

Rotates the referenced node.

NameTypeRequiredWhat it is
xnumber|Vec3yesX or vector
ynumberoptional
znumberoptional

Returns: void

enemy.rotate3D(0, 45, 0);

Watch out: Degrees per second.

#node.lookAt3D(target)

method3DVYOM

Makes the referenced node face a target.

NameTypeRequiredWhat it is
targetVec3|NodeRefyesPoint or node to face

Returns: void

enemy.lookAt3D(player);

Watch out: See lookAt3D.

#node.getPosition3D()

method3DVYOM

Position.

No parameters.

Returns: Vec3

var p = enemy.getPosition3D();

Watch out: Copy.

#node.setPosition3D(x, y?, z?)

method3DVYOM

Sets the position.

NameTypeRequiredWhat it is
xnumber|Vec3yes
ynumberoptional
znumberoptional

Returns: void

enemy.setPosition3D(1, 2, 3);

Watch out: Teleports.

#node.getRotation3D()

method3DVYOM

Rotation in degrees.

No parameters.

Returns: Vec3

var r = enemy.getRotation3D();

Watch out: Degrees.

#node.setRotation3D(x, y?, z?)

method3DVYOM

Sets the rotation in degrees.

NameTypeRequiredWhat it is
xnumber|Vec3yes
ynumberoptional
znumberoptional

Returns: void

enemy.setRotation3D(0, 180, 0);

Watch out: Degrees.

#node.setScale3D(x, y?, z?)

method3DVYOM

Sets the scale.

NameTypeRequiredWhat it is
xnumber|Vec3yes
ynumberoptional
znumberoptional

Returns: void

enemy.setScale3D(2);

Watch out: One number scales all axes.

#node.setVelocity3D(x, y?, z?)

method3DVYOM

Sets the velocity of the referenced body.

NameTypeRequiredWhat it is
xnumber|Vec3yes
ynumberoptional
znumberoptional

Returns: void

enemy.setVelocity3D(0, 0, -3);

Watch out: Needs a body node.

#node.moveAndSlide3D()

method3DVYOM

Runs moveAndSlide on the referenced CharacterBody3D.

No parameters.

Returns: boolean

enemy.moveAndSlide3D();

Watch out: Only CharacterBody3D.

#node.isOnFloor3D()

method3DVYOM

True if the referenced body is on the floor.

No parameters.

Returns: boolean

if (enemy.isOnFloor3D()) { }

Watch out: Only CharacterBody3D.

#node.isColliding3D()

method3DVYOM

True if the body collided in its last move.

No parameters.

Returns: boolean

if (enemy.isColliding3D()) { }

Watch out: Only CharacterBody3D.

#node.playAnimation3D(name)

method3DVYOM

Plays an animation of the referenced node.

NameTypeRequiredWhat it is
namestringyesAnimation name

Returns: void

enemy.playAnimation3D("walk");

Watch out: Needs an AnimationPlayer.

#node.stopAnimation3D()

method3DVYOM

Stops the animation.

No parameters.

Returns: void

enemy.stopAnimation3D();

Watch out: No-op if idle.

#node.x

property3DVYOM

Global X position (left/right). Same as position.x, but you can assign it directly.

Type: number

door.x += 0.05;

Watch out: Y is UP in 3D (not down like in 2D). Forward is -Z.

#node.y

property3DVYOM

Global Y position (height).

Type: number

lift.y = 3;

Watch out: Y is UP in 3D.

#node.z

property3DVYOM

Global Z position (forward/back; -Z is forward).

Type: number

crate.z = -10;

Watch out: Negative z is away from the default camera.

#node.setPosition(x, y?, z?)

method3DVYOM

Puts the node at x, y, z. Same as setPosition3D, written like the 2D setPosition.

NameTypeRequiredWhat it is
xnumber|Vec3yesX or a vector
ynumberoptionalY
znumberoptionalZ

Returns: Node3DRef

key.setPosition(2, 1, -4);

Watch out: Teleports: physics bodies keep their velocity.

#node.hide()

method3DVYOM

Hides the node (visible = false).

No parameters.

Returns: Node3DRef

key.hide();

Watch out: A hidden node still has collision. Use destroy() to remove it for good.

#node.show()

method3DVYOM

Shows the node again.

No parameters.

Returns: Node3DRef

key.show();

Watch out: Opposite of hide().

#node.setLight(energy?, color?, range?)

method3DVYOM

Changes an OmniLight3D, SpotLight3D or DirectionalLight3D in the scene: brightness, colour and reach. This is how you build a flashlight, a flickering lamp or a power cut.

NameTypeRequiredWhat it is
energynumberoptionalBrightness. 0 turns the light off
colorstringoptionalLight colour like "orange" or "#ffeecc"
rangenumberoptionalHow far the light reaches, in metres

Returns: void

var lamp = createObject3D("light", 0, 3, 0);
lamp.setLight(3, "orange", 12);

Watch out: The node must be a light. To switch a light on and off quickly use node.hide() and node.show().

3D touching & distance 14

#node.isTouching(target, margin?)

method3DVYOM

True if this node touches the target. The shapes used are the nodes' collision shapes (or their meshes when there are none), as real turned boxes - a rotated crate is not treated as a bigger box.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3|ArrayyesA node from getNode3D(), a point, or an array / group of them
marginnumberoptionalExtra reach in metres (default 0)

Returns: boolean

var player = getNode3D("Player");
var key = getNode3D("Key");
function update() {
  if (player.isTouching(key, 0.5)) { key.destroy(); giveItem("key"); }
}

Watch out: It only tells you; it does not stop movement (use a CharacterBody3D for solid walls). The margin makes picking things up easier: 0.5 means "within half a metre". Call getNode3D() once at the top, not every frame.

#node.isColliding(target, margin?)

method3DVYOM

Same as isTouching().

NameTypeRequiredWhat it is
targetNode3DRef|Vec3|ArrayyesTarget
marginnumberoptionalExtra reach in metres

Returns: boolean

if (enemy.isColliding(player)) { print("caught"); }

Watch out: Not the same as isColliding3D(), which asks whether the body bumped into something while moving.

#node.isOverlapping(target)

method3DVYOM

True only if the shapes really overlap (just touching surfaces do not count).

NameTypeRequiredWhat it is
targetNode3DRef|Vec3|ArrayyesTarget

Returns: boolean

if (zone.isOverlapping(player)) { print("inside the room"); }

Watch out: See isTouching.

#node.touched(target, margin?)

method3DVYOM

True when this node HAS touched the target before and is NOT touching it right now. isTouching() is only true while they touch; touched() becomes true when they separate and stays true afterwards.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3|ArrayyesTarget
marginnumberoptionalExtra reach in metres (default 0)

Returns: boolean

var player = getNode3D("Player");
var door = getNode3D("Door");
function update() {
  if (player.touched(door, 0.5)) { print("you already visited the door"); }
}

Watch out: Call it every frame: it starts watching the pair the first time you call it, so contact before that first call does not count.

#node.distanceTo(x_or_target, y?, z?)

method3DVYOM

Distance in metres from this node to a point or node.

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, a vector or the X of a point
ynumberoptionalY when the first argument is a number
znumberoptionalZ when the first argument is a number

Returns: number

if (enemy.distanceTo(player) < 10) { print("close"); }

Watch out: Straight line through the air. Use flatDistanceTo() to ignore height.

#node.flatDistanceTo(x_or_target, y?, z?)

method3DVYOM

Distance in metres on the ground (height ignored).

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, a vector or the X of a point
ynumberoptionalY (ignored)
znumberoptionalZ when the first argument is a number

Returns: number

if (granny.flatDistanceTo(player) < 1.5) { print("caught"); }

Watch out: Handy when the enemy and the player stand on different floors or the origin is at a different height.

#node.angleTo(x_or_target, y?, z?)

method3DVYOM

The turn in degrees (around Y) that makes this node face the target. 0 = looking along -Z.

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, a vector or the X of a point
ynumberoptionalY (ignored)
znumberoptionalZ

Returns: number

self.rotation = vec3(0, self.angleTo(player), 0);

Watch out: Degrees. Use faceTowards() to do it in one step.

#node.forward()

method3DVYOM

The direction this node is looking at (a vector of length 1, its -Z axis in the world).

No parameters.

Returns: Vec3

var ahead = self.position.add(self.forward().scale(2));

Watch out: A copy: it does not follow the node afterwards.

#isTouching(target, margin?)

function3DVYOM

In a script attached to a 3D node: true if that node touches the target. Same as self.isTouching(target).

NameTypeRequiredWhat it is
targetNode3DRef|Vec3|ArrayyesWhat to test against
marginnumberoptionalExtra reach in metres

Returns: boolean

var key = getNode3D("Key");
function update() {
  if (isTouching(key, 0.5)) { key.destroy(); giveItem("key"); }
}

Watch out: Only in scripts attached to a node. For other nodes use node.isTouching(target).

#isOverlapping(target)

function3DVYOM

Like isTouching() but touching surfaces do not count.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3|ArrayyesWhat to test against

Returns: boolean

if (isOverlapping(getNode3D("SafeRoom"))) { print("safe"); }

Watch out: Only in scripts attached to a node.

#touched(target, margin?)

function3DVYOM

In a script attached to a 3D node: true when that node HAS touched the target before and is not touching it right now. Same as self.touched(target).

NameTypeRequiredWhat it is
targetNode3DRef|Vec3|ArrayyesWhat to test against
marginnumberoptionalExtra reach in metres

Returns: boolean

var door = getNode3D("Door");
function update() {
  if (touched(door, 0.5)) { print("already visited the door"); }
}

Watch out: Only in scripts attached to a node. Call it every frame.

#distanceTo(x_or_target, y?, z?)

function3DVYOM

Distance in metres from the node this script is attached to.

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, vector or X
ynumberoptionalY
znumberoptionalZ

Returns: number

if (distanceTo(getNode3D("Player")) < 5) { print("near"); }

Watch out: Only in scripts attached to a node.

#flatDistanceTo(x_or_target, y?, z?)

function3DVYOM

Distance on the ground (height ignored) from the node this script is attached to.

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, vector or X
ynumberoptionalY (ignored)
znumberoptionalZ

Returns: number

if (flatDistanceTo(getNode3D("Player")) < 1.5) { print("caught"); }

Watch out: Only in scripts attached to a node.

#angleTo(x_or_target, y?, z?)

function3DVYOM

Turn in degrees that makes this node face the target.

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, vector or X
ynumberoptionalY (ignored)
znumberoptionalZ

Returns: number

setRotation3D(0, angleTo(getNode3D("Player")), 0);

Watch out: Only in scripts attached to a node.

3D enemies & AI 14

#node.faceTowards(x_or_target, y?, z?)

method3DVYOM

Turns the node around the Y axis so it looks at the target, staying level (it does not tilt up or down).

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, vector or X
ynumberoptionalY (ignored)
znumberoptionalZ

Returns: Node3DRef

enemy.faceTowards(player);

Watch out: Instant. For a smooth turn use turnTowards().

#node.turnTowards(target, degreesPerSecond)

method3DVYOM

Turns smoothly (the short way round) towards the target. Call it every frame.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3yesNode or point to turn to
degreesPerSecondnumberyesTurn speed

Returns: Node3DRef

function update() {
  enemy.turnTowards(player, 120);
}

Watch out: Speed is per second, like move3D.

#node.moveTowards(x_or_target, y_or_speed, z?, speed?)

method3DVYOM

Moves the node straight towards a point or node, never overshooting. Returns true when it arrived. moveTowards(target, speed) or moveTowards(x, y, z, speed).

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, vector or the X of a point
y_or_speednumberyesSpeed (metres per second) when a node was given, otherwise Y
znumberoptionalZ when numbers were given
speednumberoptionalSpeed when numbers were given

Returns: boolean

function update() {
  lift.moveTowards(0, 6, 0, 1.5);
}

Watch out: Goes through walls (it sets the position). Use chase() for walking enemies. Speed is per second.

#node.chase(target, speed, stopDistance?)

method3DVYOM

Walks towards the target on the ground and faces it. A CharacterBody3D slides along walls and falls with gravity (it moves itself: do not also call moveAndSlide3D for it). Returns true once it is within stopDistance.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3yesNode or point to walk to
speednumberyesMetres per second
stopDistancenumberoptionalStop this far away (default 1)

Returns: boolean

var granny = getNode3D("Granny");
var player = getNode3D("Player");
function update() {
  if (granny.chase(player, 3.5, 1.2)) { print("caught you"); }
}

Watch out: Works best with a CharacterBody3D that has a CollisionShape3D. It does not find paths around obstacles: combine it with canSee() and patrol().

#node.wander(speed, radius?, pauseSeconds?)

method3DVYOM

Strolls to random spots around where it started, pausing now and then. Call it every frame.

NameTypeRequiredWhat it is
speednumberyesMetres per second
radiusnumberoptionalHow far from its starting spot it may go (default 8)
pauseSecondsnumberoptionalPause at each spot (default 2)

Returns: void

function update() {
  if (!granny.canSee(player, 15)) { granny.wander(1.5, 10); }
}

Watch out: Uses chase(), so the node must be a CharacterBody3D to be stopped by walls.

#node.patrol(points, speed, waitSeconds?)

method3DVYOM

Walks a loop through the points, forever. Call it every frame.

NameTypeRequiredWhat it is
pointsArrayyesPoints to walk through: vec3(...), [x,y,z] or nodes
speednumberyesMetres per second
waitSecondsnumberoptionalPause at each point (default 0)

Returns: void

var route = [vec3(0, 0, 0), vec3(6, 0, 0), vec3(6, 0, -6)];
function update() {
  granny.patrol(route, 2, 1);
}

Watch out: Give the points the same height as the floor the enemy walks on.

#node.canSee(target, maxDistance?, fov?, eyeHeight?)

method3DVYOM

Line of sight: true if the target is in range and view angle and nothing solid is in between.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3yesWhat to look at
maxDistancenumberoptionalHow far it can see in metres
fovnumberoptionalField of view in degrees (default: all around)
eyeHeightnumberoptionalHeight of the eyes above the node (default 0.6)

Returns: boolean

if (granny.canSee(player, 20, 120)) { granny.chase(player, 4); } else { granny.wander(1.5); }

Watch out: Only things with collision block the view. The node looks along its -Z axis; with faceTowards()/chase() that is the way it walks.

#chase(target, speed, stopDistance?)

function3DVYOM

In a script attached to a 3D node: walk towards the target and face it. Same as self.chase().

NameTypeRequiredWhat it is
targetNode3DRef|Vec3yesNode or point
speednumberyesMetres per second
stopDistancenumberoptionalStop distance (default 1)

Returns: boolean

var player = getNode3D("Player");
function update() {
  chase(player, 3.5, 1.2);
}

Watch out: Do not also call moveAndSlide3D() for this node.

#wander(speed, radius?, pauseSeconds?)

function3DVYOM

In a script attached to a 3D node: stroll around the starting spot.

NameTypeRequiredWhat it is
speednumberyesMetres per second
radiusnumberoptionalRadius (default 8)
pauseSecondsnumberoptionalPause (default 2)

Returns: void

function update() { wander(1.5, 10); }

Watch out: Call it every frame.

#patrol(points, speed, waitSeconds?)

function3DVYOM

In a script attached to a 3D node: walk a loop through points.

NameTypeRequiredWhat it is
pointsArrayyesPoints to walk through
speednumberyesMetres per second
waitSecondsnumberoptionalPause at each point

Returns: void

var route = [vec3(0, 0, 0), vec3(5, 0, 0)];
function update() { patrol(route, 2, 1); }

Watch out: Call it every frame.

#moveTowards(x_or_target, y_or_speed, z?, speed?)

function3DVYOM

In a script attached to a 3D node: move straight towards a point (metres per second).

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, vector or X
y_or_speednumberyesSpeed or Y
znumberoptionalZ
speednumberoptionalSpeed

Returns: boolean

function update() { moveTowards(0, 5, 0, 1); }

Watch out: Goes through walls.

#faceTowards(x_or_target, y?, z?)

function3DVYOM

In a script attached to a 3D node: look at the target (staying level).

NameTypeRequiredWhat it is
x_or_targetnumber|Node3DRef|Vec3yesA node, vector or X
ynumberoptionalY (ignored)
znumberoptionalZ

Returns: Node3DRef

faceTowards(getNode3D("Player"));

Watch out: Instant.

#turnTowards(target, degreesPerSecond)

function3DVYOM

In a script attached to a 3D node: turn smoothly towards the target.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3yesNode or point
degreesPerSecondnumberyesTurn speed

Returns: Node3DRef

turnTowards(getNode3D("Player"), 90);

Watch out: Call it every frame.

#canSee(target, maxDistance?, fov?, eyeHeight?)

function3DVYOM

In a script attached to a 3D node: line of sight to the target.

NameTypeRequiredWhat it is
targetNode3DRef|Vec3yesWhat to look at
maxDistancenumberoptionalRange in metres
fovnumberoptionalField of view in degrees
eyeHeightnumberoptionalEye height (default 0.6)

Returns: boolean

if (canSee(getNode3D("Player"), 20, 120)) { print("I see you"); }

Watch out: Walls need collision shapes to block the view.

3D interaction & game state 15

#node.isLookedAt(maxDistance?)

method3DVYOM

True while the crosshair (the middle of the screen) is on this node. Perfect for "press E to pick up".

NameTypeRequiredWhat it is
maxDistancenumberoptionalHow far in metres (default 5)

Returns: boolean

if (key.isLookedAt(3) && keyWentDown("e")) { key.destroy(); giveItem("key"); }

Watch out: The node needs a collision shape (a StaticBody3D / Area3D), because the check uses a physics ray.

#node.mouseIsOver()

method3DVYOM

True while the mouse pointer (or, with captureMouse(true), the crosshair) is over this node.

No parameters.

Returns: boolean

if (button.mouseIsOver()) { showMessage("Click to open"); }

Watch out: The node needs a collision shape.

#node.mousePressedOver()

method3DVYOM

True for the one frame in which the left mouse button is clicked while over this node.

No parameters.

Returns: boolean

if (door.mousePressedOver()) { door.moveTowards(0, 4, 0, 5); }

Watch out: One frame per click.

#node.mouseHeldOver()

method3DVYOM

True every frame the left button is held down over this node.

No parameters.

Returns: boolean

if (lever.mouseHeldOver()) { lever.rotate3D(60, 0, 0); }

Watch out: See mousePressedOver.

#node.mouseReleasedOver()

method3DVYOM

True for the one frame in which the left button is released over this node.

No parameters.

Returns: boolean

if (card.mouseReleasedOver()) { print("dropped"); }

Watch out: One frame only.

#getLookTarget(distance?)

function3DVYOM

What the crosshair points at: {hit, position, normal, distance, collider} or null. In a script attached to a node, that node itself is ignored.

NameTypeRequiredWhat it is
distancenumberoptionalHow far in metres (default 5)

Returns: object|null

var look = getLookTarget(4);
if (look && look.collider.isInGroup("pickups")) { showMessage("Press E"); }

Watch out: Things need collision shapes. The camera must look from the player (first person).

#isLookingAt(node, distance?)

function3DVYOM

True while the crosshair is on that node.

NameTypeRequiredWhat it is
nodeNode3DRefyesThe node to check
distancenumberoptionalHow far in metres (default 5)

Returns: boolean

var door = getNode3D("Door");
function update() {
  if (isLookingAt(door, 3) && keyWentDown("e")) { door.moveTowards(0, 4, 0, 5); }
}

Watch out: Same limits as getLookTarget().

#setGlobal(name, value)

function3DVYOM

Stores a value that EVERY script can read with getGlobal(). (A normal var belongs to one script only.)

NameTypeRequiredWhat it is
namestringyesName of the value
valueanyyesWhat to store

Returns: any

setGlobal("hasPower", true);

Watch out: Lives until the game stops. Use it for state that several scripts share.

#getGlobal(name, fallback?)

function3DVYOM

Reads a value stored with setGlobal(), from any script.

NameTypeRequiredWhat it is
namestringyesName of the value
fallbackanyoptionalReturned when nothing was stored

Returns: any

if (getGlobal("hasPower", false)) { print("lights on"); }

Watch out: Give a fallback so you do not get undefined.

#giveItem(name, count?)

function3DVYOM

Puts an item in the inventory (shared by all scripts). Returns how many you now have.

NameTypeRequiredWhat it is
namestringyesItem name, e.g. "key"
countnumberoptionalHow many (default 1)

Returns: number

giveItem("key");
giveItem("battery", 2);

Watch out: Item names are case sensitive.

#takeItem(name, count?)

function3DVYOM

Removes items from the inventory. Returns false (and takes nothing) if you do not have enough.

NameTypeRequiredWhat it is
namestringyesItem name
countnumberoptionalHow many (default 1)

Returns: boolean

if (takeItem("key")) { print("unlocked"); } else { showMessage("The door is locked"); }

Watch out: Check the result: it is false when you do not have the item.

#hasItem(name, count?)

function3DVYOM

True if the inventory holds at least that many.

NameTypeRequiredWhat it is
namestringyesItem name
countnumberoptionalHow many you need (default 1)

Returns: boolean

if (hasItem("battery", 3)) { showMessage("Generator ready"); }

Watch out: It does not remove anything: use takeItem() for that.

#itemCount(name)

function3DVYOM

How many of an item you have (0 if none).

NameTypeRequiredWhat it is
namestringyesItem name

Returns: number

function draw() {
  text("Batteries: " + itemCount("battery"), 20, 30);
}

Watch out: Returns 0, never undefined.

#getItems()

function3DVYOM

A copy of the whole inventory as {name: count}.

No parameters.

Returns: object

var inv = getItems();
print(JSON.stringify(inv));

Watch out: A copy: changing it does not change the inventory.

#showMessage(text, seconds?)

function3DVYOM

Shows a message at the bottom of the screen for a few seconds (up to four at once). Works in every script, no draw() needed.

NameTypeRequiredWhat it is
textstringyesWhat to show
secondsnumberoptionalHow long (default 3)

Returns: void

showMessage("You found a key!");
showMessage("Run!", 1.5);

Watch out: Messages are drawn on top of the game; for a permanent HUD use text() inside draw().

3D World & camera 15

#World3D

object3DVYOM

Information about the 3D world.

Type: object

print(World3D.gravity);

Watch out: Use World for 2D.

#World3D.gravity

property3DVYOM

Project 3D gravity (default 9.8).

Type: number read-only

velocity3D.y -= World3D.gravity * dt;

Watch out: Read-only: change it in Project Settings.

#World3D.deltaTime

property3DVYOM

Seconds of the current frame.

Type: number read-only

var speed = 5 * World3D.deltaTime;

Watch out: Same as the dt passed to update().

#World3D.physicsDelta

property3DVYOM

Seconds per physics step.

Type: number read-only

print(World3D.physicsDelta);

Watch out: Usually 1/60.

#World3D.frameCount

property3DVYOM

Frames since the game started.

Type: number read-only

if (World3D.frameCount % 60 === 0) { tick(); }

Watch out: Counts frames.

#camera3D

object3DVYOM

The active 3D camera of the running scene.

Type: object

camera3D.follow(getNode3D("Player"), 0.1);

Watch out: The scene needs a Camera3D node (or create one with createObject3D("camera")).

#camera3D.position

property3DVYOM

Camera position (global).

Type: Vec3

camera3D.position = vec3(0, 5, 10);

Watch out: Assign a whole vector.

#camera3D.rotation

property3DVYOM

Camera rotation in degrees.

Type: Vec3

camera3D.rotation = vec3(-20, 0, 0);

Watch out: Degrees.

#camera3D.follow(target, smoothing?)

method3DVYOM

Keeps the camera following a node from its current offset every frame.

NameTypeRequiredWhat it is
targetNode3DRefyesNode to follow
smoothingnumberoptional0.01 to 1 (1 = snap)

Returns: void

camera3D.follow(getNode3D("Player"), 0.15);

Watch out: Pass null to stop.

#camera3D.lookAt(target)

method3DVYOM

Points the camera at a target.

NameTypeRequiredWhat it is
targetVec3|Node3DRefyesPoint or node

Returns: void

camera3D.lookAt(getNode3D("Player"));

Watch out: Call it every frame for a moving target.

#camera3D.shake(strength?, seconds?)

method3DVYOM

Shakes the picture for a moment and then calms down. Use it for jump scares, explosions or a hard landing.

NameTypeRequiredWhat it is
strengthnumberoptionalHow far the picture wobbles (0.05 = small, 0.3 = big). Default 0.1
secondsnumberoptionalHow long it lasts. Default 0.5

Returns: void

camera3D.shake(0.2, 0.8);   // the monster roars

Watch out: It wobbles the picture only; it does not move the camera node or the player.

#World3D.setFog(density, color?)

method3DVYOM

Fills the 3D world with fog. Dark thick fog is the classic horror look: you only see a few metres ahead.

NameTypeRequiredWhat it is
densitynumberyes0.02 = light mist, 0.1 = medium, 0.3 or more = very thick (you see only a few metres), 0 = no fog
colorstringoptionalFog colour like "black" or "#223344"

Returns: void

World3D.setFog(0.08, "#10141a");

Watch out: Fog colour should match the sky colour (setSkyColor) or the edge of the world looks strange. For a really dark level also make the Sun (DirectionalLight3D) dim with setLight(0.05), or delete it.

#World3D.fogOff()

method3DVYOM

Turns the fog off again.

No parameters.

Returns: void

World3D.fogOff();

Watch out: Fog is on only after setFog().

#World3D.setAmbientLight(color, energy?)

method3DVYOM

Sets how bright the shadows are. A very low value makes the world dark so that your flashlight and lamps matter.

NameTypeRequiredWhat it is
colorstringyesColour of the light that reaches everywhere, like "#202838"
energynumberoptionalBrightness, 1 = normal, 0 = pitch dark. Default 1

Returns: void

World3D.setAmbientLight("#1a1f2b", 0.3);

Watch out: Dark rooms still need a light you can see by (a SpotLight3D flashlight or an OmniLight3D lamp).

#World3D.setSkyColor(color)

method3DVYOM

Replaces the sky by one plain colour (for example black for a night scene or an indoor level).

NameTypeRequiredWhat it is
colorstringyesColour of the sky / background

Returns: void

World3D.setSkyColor("black");

Watch out: Use the same colour as the fog.

Engine 17

#loadScene(name)

function2D + 3DVYOM

Loads another scene of your project by its name. The game switches to it at the end of the frame and the new scene's scripts start from the top. Returns true when the scene was found, false (and a message in the Output) when there is no scene with that name. You can also write load_scene("game").

NameTypeRequiredWhat it is
namestringyesName of the scene: "game", "Game" or "game.tscn" (or a full path like "res://scenes/game.tscn")

Returns: boolean

var button;
function start() {
  button = createSprite(200, 200, 120, 40);
}
function draw() {
  if (mousePressedOver(button)) {
    loadScene("game");
  }
}

Watch out: The name is the scene file name without .tscn (the tab name in the editor); capitals do not matter. Save the scene first: unsaved scenes have no file. Variables of the old scene are gone - use setGlobal / getGlobal to carry values (a score) over to the next scene.

#changeScene(path)

function2D + 3DVYOM

Same as loadScene(): switches to another scene at the end of the frame.

NameTypeRequiredWhat it is
pathstringyesScene file, e.g. "res://scenes/level2.tscn" (a plain name like "level2" works too)

Returns: boolean

if (World.frameCount > 100) { changeScene("res://scenes/level2.tscn"); }

Watch out: Variables are lost and the new scene's scripts start again; setGlobal values stay. Prefer loadScene("level2").

#quitGame()

function2D + 3DVYOM

Closes the game.

No parameters.

Returns: void

if (keyDown("escape")) { quitGame(); }

Watch out: In the editor this stops the play session.

#saveData(key, value)

function2D + 3DVYOM

Saves something so it is still there the next time the game is played: a high score, the level you reached, the settings. It is kept in a small file on the player's computer (in the browser for the web version).

NameTypeRequiredWhat it is
keystringyesA name for this saved thing, like "highscore"
valueanyyesA number, text, true/false, list or object

Returns: boolean

if (score > loadData("highscore", 0)) { saveData("highscore", score); }

Watch out: Saved data stays after the game closes. Use deleteData to forget it. Functions cannot be saved.

#loadData(key, fallback?)

function2D + 3DVYOM

Reads back something saved with saveData. If nothing was saved yet you get the fallback value.

NameTypeRequiredWhat it is
keystringyesThe name you used in saveData
fallbackanyoptionalWhat you get back when nothing was saved yet

Returns: any

var best = loadData("highscore", 0);
var name = loadData("playerName", "Player");

Watch out: Always give a fallback (like 0), because the very first time the game is played nothing is saved yet.

#hasData(key)

function2D + 3DVYOM

True if something is saved under that name.

NameTypeRequiredWhat it is
keystringyesThe name you used in saveData

Returns: boolean

if (hasData("level")) { print("Welcome back!"); }

Watch out: Names are case sensitive: "Level" and "level" are different.

#deleteData(key?)

function2D + 3DVYOM

Deletes a saved value (or all saved values when you give no name). Use it for a "New game" button.

NameTypeRequiredWhat it is
keystringoptionalWhat to forget. Leave empty to forget everything

Returns: void

deleteData("level");   // one thing
deleteData();           // everything

Watch out: This cannot be undone.

#setFullscreen(on?)

function2D + 3DVYOM

Switches the game window between fullscreen and a normal window.

NameTypeRequiredWhat it is
onbooleanoptionaltrue = fullscreen, false = back to a window. Default true

Returns: void

if (keyWentDown("f")) { setFullscreen(true); }
if (keyWentDown("escape")) { setFullscreen(false); }

Watch out: Does nothing in the editor's Game tab (only in a real game window) and in the web version the browser may ask the player first.

#setTimeout(fn, ms)

function2D + 3DGame Lab-style

Calls a function once after a delay (game time).

NameTypeRequiredWhat it is
fnfunctionyesFunction to call
msnumberyesDelay in milliseconds

Returns: number

setTimeout(function () { player.visible = true; }, 2000);

Watch out: Time only advances while the game runs; it pauses with the game.

#setInterval(fn, ms)

function2D + 3DGame Lab-style

Calls a function repeatedly.

NameTypeRequiredWhat it is
fnfunctionyesFunction to call
msnumberyesInterval in milliseconds

Returns: number

var id = setInterval(spawnEnemy, 1000);

Watch out: Clear it with clearInterval(id).

#clearTimeout(id)

function2D + 3DGame Lab-style

Cancels a timeout.

NameTypeRequiredWhat it is
idnumberyesId from setTimeout

Returns: void

clearTimeout(id);

Watch out: Unknown ids are ignored.

#clearInterval(id)

function2D + 3DGame Lab-style

Cancels an interval.

NameTypeRequiredWhat it is
idnumberyesId from setInterval

Returns: void

clearInterval(id);

Watch out: Unknown ids are ignored.

#print(values...)

function2D + 3DGame Lab-style

Writes to the Output panel.

NameTypeRequiredWhat it is
values...anyyesThings to show

Returns: void

print("score", score);

Watch out: Objects are shown as JSON.

#console.log(values...)

function2D + 3DGame Lab-style

Same as print().

NameTypeRequiredWhat it is
values...anyyesThings to show

Returns: void

console.log("hi");

Watch out: Same output as print(); pick one style and stay with it.

#console.info(values...)

function2D + 3DGame Lab-style

Like print() with an info mark.

NameTypeRequiredWhat it is
values...anyyesThings to show

Returns: void

console.info("loaded");

Watch out: Shown in the Output panel only; it is not an error or warning.

#console.warn(values...)

function2D + 3DGame Lab-style

Writes a warning (yellow) that also appears in the Warnings tab.

NameTypeRequiredWhat it is
values...anyyesThings to show

Returns: void

console.warn("low health");

Watch out: Warnings do not stop the game.

#console.error(values...)

function2D + 3DGame Lab-style

Writes an error (red) that appears in the Errors tab.

NameTypeRequiredWhat it is
values...anyyesThings to show

Returns: void

console.error("bad state");

Watch out: It does not stop the game; thrown errors do.

Sound 25

#playSound(name, volume?, options?)

function2D + 3DGame Lab-style

Plays a sound effect. Give it the name of a sound you made in the Sound Editor (it remembers volume, fades, trim, pitch and more), or just the file name of a .wav / .ogg / .mp3 in your project. The sound plays on the "sfx" group, so setSfxVolume() changes all effects together. Options (all optional): volume (0 to 1, more is louder), pitch (1 = normal, 2 = one octave higher), pan (-1 left to 1 right), loop (true/false), fadeIn (seconds), fadeOut (seconds at the end), delay (seconds before it starts), start / end (play only this part of the file, in seconds), bus ("sfx", "music", "ui" or "voice"), pitchRandom (random +/- semitones, so repeated sounds do not sound identical), volumeRandom (0 to 1, random quieter), maxVoices (how many copies may play at once, default 8), cooldown (seconds that must pass before it can play again).

NameTypeRequiredWhat it is
namestring|string[]yesA sound from the Sound Editor ("coin"), a file name ("jump.wav" or "assets/jump.wav"), or a list of names to pick one at random
volumenumber|boolean|objectoptionalVolume 0 to 1, true to loop (Game Lab style), or an options object like { volume: 0.5, pitchRandom: 2 }
optionsobject|booleanoptionalOptions object (when the second value is a volume) or true to loop

Returns: SoundRef – The playing sound (use it to fade or stop it). Never null: a sound that could not play is a silent reference.

playSound("coin");
playSound("jump.wav", 0.8);
playSound("hit", { volume: 0.6, pitchRandom: 2 });   // slightly different every time
playSound(["step1", "step2", "step3"]);           // picks one at random
var engine = playSound("engine", { loop: true });
engine.fadeOut(1);

Watch out: Write the name without the folder if the file name is unique ("coin" finds assets/coin.wav). A misspelt name shows a message listing the sounds you have. Sounds in a loop keep playing until you stop() them. Calling playSound() every frame in draw() restarts it every frame: use playSoundWhen() instead.

#playSoundAt(name, x, y?, z?, options?)

function2D + 3DVYOM

Plays a sound at a place in the world. In a 2D game it gets quieter and moves to the left or right speaker the further the place is from the camera. In a 3D game it uses real 3D sound relative to the camera. Move the sound with sound.setPosition().

NameTypeRequiredWhat it is
namestring|string[]yesSound name or file
xnumber|Sprite|NodeyesX position, or a sprite / node to play the sound from
ynumberoptionalY position
znumberoptionalZ position (3D games only)
optionsobjectoptionalSame options as playSound, plus range (how far it can be heard)

Returns: SoundRef – The playing sound

var boom = playSoundAt("explosion", enemy.x, enemy.y);
playSoundAt("door", door);                       // from a sprite
playSoundAt("growl", 4, 1, -10, { range: 25 });   // 3D

Watch out: In 2D the "listener" is the camera (or the middle of the screen). Use setSoundListener() to change it. range is in pixels (2D) or metres (3D).

#playMusic(name, options?)

function2D + 3DVYOM

Plays a music track on the "music" group. Only one track plays at a time: starting another one cross-fades (the old track fades out while the new one fades in, crossfade seconds, default 1). Asking for the track that is already playing does nothing. Music loops by default and keeps playing when you load another scene.

NameTypeRequiredWhat it is
namestringyesMusic name or file
optionsobjectoptional{ volume, fadeIn, crossfade, loop, pitch } - same options as playSound

Returns: SoundRef – The music

playMusic("menu_theme");
// later, in the game scene:
playMusic("level1", { volume: 0.6, crossfade: 2 });

Watch out: Use stopMusic() to end it. Music is not stopped by loadScene(), on purpose, so a menu track can carry on into the game.

#stopMusic(fade?)

function2D + 3DVYOM

Fades the music out and stops it.

NameTypeRequiredWhat it is
fadenumberoptionalSeconds to fade out (default 1)

Returns: boolean – true when music was playing

if (player.health <= 0) { stopMusic(2); }

Watch out: Pass 0 to stop immediately.

#stopSound(what?, fade?)

function2D + 3DGame Lab-style

Stops one sound by name (all copies of it), one SoundRef, or every sound.

NameTypeRequiredWhat it is
whatstring|SoundRef|numberoptionalSound name, a SoundRef, or nothing for every sound (music too)
fadenumberoptionalSeconds to fade out (default 0 = at once)

Returns: boolean – true when something was stopped

stopSound("engine", 0.5);
stopSound();          // everything
stopSound(mySound);

Watch out: Nothing happens (and there is no error) when the sound is not playing.

#fadeSound(what, volume, seconds?)

function2D + 3DVYOM

Smoothly changes the volume of a playing sound.

NameTypeRequiredWhat it is
whatstring|SoundRefyesSound name or a SoundRef
volumenumberyesVolume to fade to (0 to 1)
secondsnumberoptionalHow long the fade takes (default 1)

Returns: boolean – true when a playing sound was found

fadeSound("rain", 0.1, 2);   // quiet rain over 2 seconds

Watch out: To fade a whole group (all music, all effects) use setMusicVolume(v, seconds) / setSfxVolume(v, seconds).

#pauseSounds()

function2D + 3DVYOM

Pauses every playing sound (for a pause menu). The game's own Pause button pauses sounds too.

No parameters.

Returns: void

if (keyWentDown("p")) { pauseSounds(); }

Watch out: Resume with resumeSounds().

#resumeSounds()

function2D + 3DVYOM

Continues sounds paused with pauseSounds().

No parameters.

Returns: void

if (keyWentDown("o")) { resumeSounds(); }

Watch out: Sounds paused individually with sound.pause() are also resumed.

#setMasterVolume(volume, fade?)

function2D + 3DVYOM

Sets the loudness of the whole game: every sound and the music.

NameTypeRequiredWhat it is
volumenumberyes0 (silent) to 1 (normal), up to 2
fadenumberoptionalSeconds to fade (default 0)

Returns: void

setMasterVolume(0.5);
setMasterVolume(0, 2);   // fade everything to silence

Watch out: This is a volume setting for the player (like an options menu). Use setMusicVolume / setSfxVolume for one group.

#setMusicVolume(volume, fade?)

function2D + 3DVYOM

Sets the loudness of all music.

NameTypeRequiredWhat it is
volumenumberyes0 to 1
fadenumberoptionalSeconds to fade (default 0)

Returns: void

setMusicVolume(0.3);

Watch out: Only affects music started with playMusic() or sounds with bus: "music".

#setSfxVolume(volume, fade?)

function2D + 3DVYOM

Sets the loudness of all sound effects.

NameTypeRequiredWhat it is
volumenumberyes0 to 1
fadenumberoptionalSeconds to fade (default 0)

Returns: void

setSfxVolume(0.7);

Watch out: Only affects the "sfx" group (the default for playSound).

#setBusVolume(bus, volume, fade?)

function2D + 3DVYOM

Sets the loudness of one sound group (a "bus"). Every sound belongs to a group: sfx (default), music, ui (button clicks) or voice (speech).

NameTypeRequiredWhat it is
busstringyes"master", "music", "sfx", "ui" or "voice"
volumenumberyes0 to 1
fadenumberoptionalSeconds to fade (default 0)

Returns: void

setBusVolume("ui", 0.5);
setBusVolume("voice", 1, 0.5);

Watch out: A misspelt group name shows a message with the valid names.

#getBusVolume(bus)

function2D + 3DVYOM

Reads the volume of a sound group, for example to draw a volume slider.

NameTypeRequiredWhat it is
busstringyes"master", "music", "sfx", "ui" or "voice"

Returns: number – The volume (0 to 1)

text("Music: " + Math.round(getBusVolume("music") * 100) + "%", 10, 20);

Watch out: It returns the volume you set (the target while a fade is running).

#getMasterVolume()

function2D + 3DVYOM

Reads the master volume.

No parameters.

Returns: number – The master volume

if (keyWentDown("up")) { setMasterVolume(Math.min(1, getMasterVolume() + 0.1)); }

Watch out: Same as getBusVolume("master").

#muteSounds(on?)

function2D + 3DVYOM

Mutes or unmutes the whole game without changing the volume setting.

NameTypeRequiredWhat it is
onbooleanoptionaltrue to mute, false to unmute (default true)

Returns: void

if (keyWentDown("m")) { muteSounds(!muted); muted = !muted; }
var muted = false;

Watch out: Muted sounds keep playing silently, so they are in the right place when you unmute.

#muteBus(bus, on?)

function2D + 3DVYOM

Mutes one sound group.

NameTypeRequiredWhat it is
busstringyes"master", "music", "sfx", "ui" or "voice"
onbooleanoptionaltrue to mute (default true)

Returns: void

muteBus("music", true);

Watch out: Unmute with muteBus("music", false).

#duckMusic(level?, seconds?)

function2D + 3DVYOM

Lowers the music for a moment (called "ducking") so speech or an important sound can be heard. Undo it with unduckMusic().

NameTypeRequiredWhat it is
levelnumberoptionalHow loud the music stays, 0 to 1 (default 0.3)
secondsnumberoptionalFade time (default 0.3)

Returns: void

playSound("announcer", { bus: "voice" });
duckMusic(0.3);
setTimeout(unduckMusic, 3000);

Watch out: Ducking multiplies with setMusicVolume, it does not replace it.

#unduckMusic(seconds?)

function2D + 3DVYOM

Brings the music back to its normal volume after duckMusic().

NameTypeRequiredWhat it is
secondsnumberoptionalFade time (default 0.5)

Returns: void

unduckMusic(1);

Watch out: Does nothing if the music was not ducked.

#playSoundWhen(condition, name, options?)

function2D + 3DVYOM

Plays a sound ONCE each time the condition BECOMES true. You can put it straight in draw() or update(): it does not play again every frame while the condition stays true, only when it turns from false to true again.

NameTypeRequiredWhat it is
conditionbooleanyesSomething that is true or false, like player.isTouching(coin)
namestring|string[]yesSound name or file
optionsobjectoptionalSame options as playSound

Returns: SoundRef|null – The sound when it started this frame, otherwise null

playSoundWhen(player.isTouching(coin), "coin");
playSoundWhen(keyWentDown("space"), "jump");
playSoundWhen(player.y > 400, "fall");

Watch out: Use a different sound name (or the same name only once) per condition: each name remembers its own last true/false state.

#playSoundWhile(condition, name, options?)

function2D + 3DVYOM

Loops a sound while the condition is true and fades it out when it turns false. Good for footsteps, an engine, a laser beam or a rain loop.

NameTypeRequiredWhat it is
conditionbooleanyesSomething that is true or false
namestringyesSound name or file (it loops)
optionsobjectoptionalSame options as playSound

Returns: SoundRef|null – The looping sound while the condition is true

playSoundWhile(keyDown("right") || keyDown("left"), "footsteps", { volume: 0.5 });

Watch out: Call it every frame (in update or draw). It starts the sound once and keeps it going, it does not restart it.

#soundExists(name)

function2D + 3DVYOM

Tells whether a sound (preset or file) can be found.

NameTypeRequiredWhat it is
namestringyesSound name or file

Returns: boolean

if (!soundExists("boom")) { print("add boom.wav to the project"); }

Watch out: It checks the name, it does not play anything.

#getSoundLength(name)

function2D + 3DVYOM

How long a sound file is.

NameTypeRequiredWhat it is
namestringyesSound name or file

Returns: number – Length in seconds (0 if not found)

var secs = getSoundLength("jingle");

Watch out: It is the length of the whole file, not the trimmed part.

#isSoundPlaying(name)

function2D + 3DVYOM

Tells whether a sound is playing right now.

NameTypeRequiredWhat it is
namestringyesSound name or file

Returns: boolean

if (!isSoundPlaying("siren")) { playSound("siren"); }

Watch out: A paused sound counts as not playing.

#getPlayingSounds()

function2D + 3DVYOM

Lists the sounds that are playing right now (handy to debug).

No parameters.

Returns: string[] – Names of the sounds playing now

print(getPlayingSounds());

Watch out: The same name appears once for every copy that is playing.

#setSoundListener(x?, y?)

function2DVYOM

Sets where the player "hears" from in a 2D game, used by playSoundAt(). By default it is the camera, or the middle of the screen.

NameTypeRequiredWhat it is
xnumber|Sprite|NodeoptionalX position, or a sprite to listen from. Pass nothing to follow the camera again
ynumberoptionalY position

Returns: void

setSoundListener(player);

Watch out: In 3D the active camera is the listener automatically.

Sound references 15

#sound.stop(fade?)

method2D + 3DVYOM

Stops this sound (optionally with a fade-out).

NameTypeRequiredWhat it is
fadenumberoptionalSeconds to fade out (default 0)

Returns: SoundRef

var s = playSound("engine", { loop: true });
s.stop(0.5);

Watch out: After stop() the reference is finished: playing again needs a new playSound().

#sound.pause()

method2D + 3DVYOM

Pauses this sound where it is.

No parameters.

Returns: SoundRef

s.pause();

Watch out: Continue with resume().

#sound.resume()

method2D + 3DVYOM

Continues a paused sound.

No parameters.

Returns: SoundRef

s.resume();

Watch out: Nothing happens if the sound was not paused.

#sound.fadeTo(volume, seconds?)

method2D + 3DVYOM

Smoothly changes the volume of this sound.

NameTypeRequiredWhat it is
volumenumberyesVolume to reach (0 to 1)
secondsnumberoptionalHow long the fade takes (default 1)

Returns: SoundRef

s.fadeTo(0.2, 1.5);

Watch out: The sound keeps playing at the new volume.

#sound.fadeOut(seconds?)

method2D + 3DVYOM

Fades the sound to silence, then stops it.

NameTypeRequiredWhat it is
secondsnumberoptionalFade time (default 1)

Returns: SoundRef

s.fadeOut(2);

Watch out: Same as stop(seconds).

#sound.setPosition(x, y?, z?)

method2D + 3DVYOM

Moves a sound made with playSoundAt(). Call it every frame for a moving thing.

NameTypeRequiredWhat it is
xnumber|Sprite|NodeyesX position or a sprite / node
ynumberoptionalY position
znumberoptionalZ position (3D)

Returns: SoundRef

var s = playSoundAt("motor", car.x, car.y, { loop: true });
function update() { s.setPosition(car); }

Watch out: Only sounds started with playSoundAt() have a position.

#sound.volume

property2D + 3DVYOM

Current volume (0 to 1, more is louder). You can set it.

Type: number

s.volume = 0.5;

Watch out: To change it smoothly use fadeTo().

#sound.pitch

property2D + 3DVYOM

Playback speed and pitch: 1 is normal, 2 is an octave higher and twice as fast. You can set it.

Type: number

engine.pitch = 1 + speed / 10;

Watch out: Higher pitch also makes the sound shorter.

#sound.pan

property2D + 3DVYOM

Left / right balance: -1 left, 0 middle, 1 right. You can set it.

Type: number

s.pan = -1;

Watch out: Not used by 3D sounds, they pan by themselves.

#sound.loop

property2D + 3DVYOM

true when the sound repeats. You can set it.

Type: boolean

s.loop = false;   // let it finish

Watch out: Setting loop to false lets the sound end naturally.

#sound.isPlaying

property2D + 3DVYOM

true while the sound is playing (a paused or finished sound is false).

Type: boolean read-only

if (!s.isPlaying) { s = playSound("music"); }

Watch out: Read only.

#sound.isPaused

property2D + 3DVYOM

true while the sound is paused.

Type: boolean read-only

if (s.isPaused) { s.resume(); }

Watch out: Read only.

#sound.time

property2D + 3DVYOM

Where the sound is, in seconds.

Type: number read-only

text(s.time.toFixed(1), 10, 20);

Watch out: Read only.

#sound.length

property2D + 3DVYOM

Length of the sound file in seconds.

Type: number read-only

var left = s.length - s.time;

Watch out: Read only.

#sound.name

property2D + 3DVYOM

The name you gave playSound().

Type: string read-only

print(s.name);

Watch out: Read only.

Game Lab compatibility

Of the 490 documented commands: 191 are original Game Lab names, 73 are adapted, 226 are engine-specific.

Compatibility is claimed only for what is implemented and tested in this engine; it is not a guarantee that every Game Lab program runs unchanged. Known differences:

TopicDifference
Game loopGame Lab runs the whole program as draw(). Nova runs the script once (top-level code, then start()), then calls update(dt) and draw() every frame (30 per second by default in 2D, 60 in 3D).
Screen sizeGame Lab is always 400x400. In Nova it is set in Project Settings; read it with World.width / World.height.
sprite.mirrorXGame Lab: sprite.mirrorX(-1) (a function). Nova: sprite.mirrorX = true (a property; -1 also works when assigned).
Images and animationsUse loadAnimation("assets/a.png", "assets/b.png"), loadSpriteSheet() or an animation saved with the Sprite Sheet Animation Editor and refer to it by its name with setAnimation("name").
SoundsplaySound("jump.wav") plays a file from the project (or a sound made in the Sound Editor); playSound(name, true) loops like in Game Lab. Nova adds music, volume groups, fades, pitch and positional sound: see the Sound section.
Collision shapesColliders do not rotate (same as Game Lab). sprite.debug = true shows them.
Whole numbersrandom() is p5-style (decimals). Game Lab's randomNumber(min, max) returns whole numbers and is available.
ErrorsErrors are shown in the Output/Errors panels with the file name and line number.

Game Lab commands that are not implemented (the engine does not define them; calling one gives a "... is not defined" error):

Game Lab commandInstead
playSpeech(text, gender, language)Text to speech is not available.
getTime(unit)Use World.seconds, World.frameCount or JavaScript's Date.now() instead.
getKeyValue / setKeyValue / deleteKeyValueGame Lab's online key-value storage does not exist offline.
showMobileControls()No on-screen touch controls.
regularPolygon / starDraw polygons with triangle()/line(), or use sprites.
textFont()The text font cannot be changed; only textSize() and textAlign().
Sound/asset library URLs ("sound://...", "asset://...")Assets are files in your project folder: assets/hero.png, assets/jump.wav.

Original Game Lab commands implemented here (same name):

draw, createSprite, createGroup, createEdgeSprites, drawSprites, drawSprite, edges, leftEdge, rightEdge, topEdge, bottomEdge, Sprite.x, Sprite.y, Sprite.width, Sprite.height, Sprite.scale, Sprite.rotation, Sprite.rotationSpeed, Sprite.depth, Sprite.visible, Sprite.lifetime, Sprite.debug, Sprite.shapeColor, Sprite.velocityX, Sprite.velocityY, Sprite.maxSpeed, Sprite.friction, Sprite.immovable, Sprite.mass, Sprite.bounciness, Sprite.animation, Sprite.setAnimation, Sprite.addAnimation, Sprite.changeAnimation, Sprite.setCollider, Sprite.collide, Sprite.overlap, Sprite.bounce, Sprite.bounceOff, Sprite.displace, Sprite.isTouching, Sprite.setSpeedAndDirection, Sprite.setVelocity, Sprite.pointTo, Sprite.destroy, Group.length, Group.add, Group.remove, Group.contains, Group.get, Group.clear, Group.maxDepth, Group.minDepth, Group.setVelocityEach, Group.setColorEach, Group.setLifetimeEach, Group.setAnimationEach, Group.destroyEach, Group.collide, Group.overlap, Group.bounce, Group.bounceOff, Group.displace, Group.isTouching, World.allSprites, loadAnimation, loadSpriteSheet, loadImage, Animation.frameDelay, Animation.looping, Animation.visible, Animation.scale, Animation.rotation, Animation.play, Animation.stop, Animation.rewind, Animation.nextFrame, Animation.previousFrame, Animation.changeFrame, Animation.getFrame, Animation.getFrameCount, Animation.getWidth, Animation.getHeight, Animation.isPlaying, camera, camera.x, camera.y, camera.zoom, camera.position, camera.on, camera.off, camera.mouseX, camera.mouseY, World, World.width, World.height, World.frameCount, World.seconds, World.frameRate, World.gravity, World.mouseX, World.mouseY, frameRate, background, clear, fill, noFill, stroke, noStroke, strokeWeight, rect, ellipse, circle, line, point, triangle, arc, text, textSize, textAlign, image, imageMode, rectMode, ellipseMode, push, pop, CENTER, CORNER, CORNERS, RADIUS, LEFT, RIGHT, TOP, BOTTOM, BASELINE, DEGREES, RADIANS, PI, TWO_PI, HALF_PI, QUARTER_PI, keyDown, keyWentDown, keyWentUp, mouseDown, mouseWentDown, mouseWentUp, mouseIsPressed, mouseIsOver, mousePressedOver, mouseX, mouseY, pmouseX, pmouseY, randomNumber, rgb, rgba, map, dist, constrain, lerp, round, floor, ceil, abs, sqrt, pow, sin, cos, tan, asin, acos, atan, atan2, degrees, radians, min, max, sq, log, exp, mag, norm, angleMode, Group.setDepthEach, Group.setRotationEach, Group.setRotationSpeedEach, Group.setScaleEach, Group.setVisibleEach, Group.setSpeedAndDirectionEach, mouseDidMove

Migration guide: Game Lab → VYOM Engine

  1. Paste your Game Lab code into a new .js file of a 2D project and attach it to the root node (the templates Empty 2D and 2D Platformer already have a script).
  2. Game Lab code at the top of the file and inside function draw() {...} keeps working. Code that must run every frame can stay in draw(); code that handles input and rules may also go to update().
  3. Replace asset URLs ("sound://...", "asset://...") with project files: drag your images/sounds into the FileSystem dock, then use assets/yourfile.png.
  4. Replace the commands listed under not implemented above.
  5. Check the Known differences table: sprite.mirrorX(-1) becomes sprite.mirrorX = true, and the world size comes from Project Settings.
  6. Run the project. Errors show the exact file and line.

Common errors

MessageMeaning and fix
X is not definedThe name does not exist: a typo, a variable declared in another script, or a command that is not implemented (see the compatibility table). Names are case sensitive.
Cannot set properties of null (setting 'velocityY') or Cannot read properties of nullA variable is empty. Most often getNode("name") did not find a node with that name, so it returned null. Look at the warning above the error in the Output: it lists the real node names in the scene and suggests the right one. Names must match exactly (capital letters count).
Cannot read properties of undefined (reading 'x')A variable was never assigned: for example a sprite created in start() used before start() ran, or getNode("Wrong/Path") returned null.
createSprite() makes 2D Game Lab sprites. This is a 3D scene ...You used a 2D command in a 3D project. Use createObject3D() / getNode3D().
createObject3D() is a 3D command, but this project is running a 2D sceneYou used a 3D command in a 2D project. Use createSprite() / getNode().
move3D() works on 3D nodes, but this script is attached to a ...Attach the script to a Node3D (or a child of one), not to a 2D node or a Control.
Sprites do not appearCall drawSprites() in draw(); check that the sprite is inside the screen (0..World.width, 0..World.height) and visible is true.
Sprite falls through the groundUse collide() every frame (it only pushes the sprite you call it on) and make the ground immovable = true.
Unexpected token / SyntaxErrorA missing bracket or quote; the line number points to where the problem was noticed, often one line after the real mistake.
Animation not found (warning)The label was not added to the sprite and there is no animations/<label>.anim.json file. Check the spelling in the Animation editor.
Nothing happens on keyDownClick the game window once to give it keyboard focus. Key names: "LEFT_ARROW", "a", "space", "enter", "shift".
Exported variable not shown in the InspectorThe line must be a top-level var name = value; // @export (not let, not inside a function).