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.
490 COMMANDS
367 FOR 2D GAMES
260 FOR 3D GAMES
22 CATEGORIES
Getting started Create a project (Project Manager → New Project → choose a template). In the FileSystem dock double-click a .js file (or Scene dock → Attach script on a node) to open it in the script editor. 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 One script per node. A script is a .js file attached to a node of a scene. Each script runs in its own sandbox: variables of one script are not visible in another one. Use getNode() / findNode() and node references to talk to other nodes.Lifecycle. The script body runs once, then start() is called once, then every frame update(dt) and draw(). Collision callbacks onCollision(other), onAreaEntered(other), onAreaExited(other) are called by the physics engine.Frame rate. 2D scripts run at 30 frames per second by default (like Game Lab; change with frameRate()); 3D scripts at 60. Sprite speeds are pixels per frame , 3D speeds (move3D, rotate3D, velocity3D) are per second and use dt internally.Coordinates. 2D: x grows to the right, y grows down , sprites are positioned by their center. 3D: x right, y up , -z forward (Godot convention); rotations are in degrees.Both worlds. A 2D scene gives the 2D commands (sprites, drawing); a 3D scene gives the 3D commands. Using a 3D command in a 2D scene (or the other way around) stops with a clear error message that says what to use instead.Exported variables. Put // @export at the end of a top-level var line to make it editable in the Inspector (var speed = 5; // @export [1,20,1] adds a range). Exported values override the value in the script before start() runs, so use top-level var, not let/const.Animation library. The Sprite Sheet Animation Editor (Asset view → Animation editor ) saves animations/<name>.anim.json. sprite.setAnimation("name") and loadAnimation("name") find those animations by name.Saving. saveData("highscore", 120) keeps a value on the player's computer (in the browser for the web version) and loadData("highscore", 0) reads it back the next time the game is played. hasData and deleteData complete the set; setFullscreen(true) switches the window to fullscreen.Errors. Syntax errors and run-time errors are reported as file.js:LINE message in the Output and Errors panels and as a red marker in the script editor. A script with an error is stopped; the other scripts keep running.
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 .
Draw pixel art: Pencil (B), Eraser (E), Fill (G), Colour picker (I), Line (L), Rectangle (R), Ellipse (O). Right-click erases, Alt-click picks a colour, Mirror draws symmetrically. Ctrl+Z / Ctrl+Y undo and redo.Edit a picture you imported: Open picture... (or right-click it in the FileSystem). If it has a plain background press Remove background : the colour at the picture border is deleted (add Also remove enclosed holes for gaps inside the art, or use the Magic eraser (W) and click a colour to delete it). Pictures that already have a see-through background are left alone.Crop so touching is exact: press Trim to art to cut every frame down to the visible pixels, or use the Crop tool (C): drag a box and press Enter. Canvas size... , Scale... and Flip are next to it. The panel tells you the size of the visible art.Animate (many frames): the FRAMES bar at the bottom holds every frame. Press + Add frame (copy) (key N) or the big + tile to add a frame, then change it a little (move the legs, turn the wheel...). + Blank frame (M) adds an empty one, Move reorders, Delete removes. Onion skin shows the previous frame, and the Preview plays your animation. Frame delay = game frames between pictures (bigger = slower). Open sheet... cuts an existing sprite sheet into frames.Quick animation: Quick animation... makes a whole animation from one picture: Spin (wheel, tire, coin), Bounce (a run / walk bob), Sway , Grow & shrink , Blink . Undo it with Ctrl+Z and edit any frame afterwards.3D animations: select an AnimationPlayer node, open the Animation tab at the bottom and press Quick animation... (spin, bounce, rock, slide, swing open, pulse) for any 3D or 2D node. For your own poses: move the node, move the playhead, press Key pose (position + rotation + scale), repeat, then Play. In a game use playAnimation3D("name").Save: the sprite is saved as assets/sprites/<name>.png (a sprite sheet) and animations/<name>.anim.json. Use it with sprite.setAnimation("<name>"), loadImage("assets/sprites/<name>.png"), or drag the PNG into a Sprite2D.
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
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.
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().
Name Type Required What it is dtnumberoptional Seconds 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() { ... }
callback 2D Game 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) { ... }
callback 2D + 3D VYOM
Called on a script attached to a physics body (CharacterBody, RigidBody, StaticBody) when the body starts touching another body. `other` is a node reference.
Name Type Required What it is otherNodeyes The 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) { ... }
callback 2D + 3D VYOM
Called on a script attached to an Area2D/Area3D node when another body enters the area.
Name Type Required What it is otherNodeyes The 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) { ... }
callback 2D + 3D VYOM
Called on a script attached to an Area2D/Area3D node when another body leaves the area.
Name Type Required What it is otherNodeyes The 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?)
function 2D Game Lab
Creates a sprite: a movable rectangle (or animation) with position, velocity and collision. A new sprite gets a random color.
Name Type Required What it is xnumberoptional Horizontal center (default 0) ynumberoptional Vertical center (default 0) widthnumberoptional Width in pixels (default 100) heightnumberoptional Height 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()
function 2D Game 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()
function 2D Game 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?)
function 2D Game Lab
Draws all sprites (sorted by depth) with the camera applied. Call it once per frame inside draw() after background().
Name Type Required What it is groupGroupoptional Only 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)
function 2D Game Lab
Draws a single sprite.
Name Type Required What it is spriteSpriteyes The 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)
function 2D Game Lab-style
Removes (destroys) a sprite. Same as sprite.destroy().
Name Type Required What it is spriteSpriteyes The 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.
Group with the four edge sprites. Defined after createEdgeSprites().
Type: Group
createEdgeSprites();
ball.bounceOff(edges);
Watch out: Undefined until createEdgeSprites() has been called.
# leftEdge
object 2D Game 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
object 2D Game Lab
The invisible sprite at the right edge.
Type: Sprite
createEdgeSprites();
player.collide(rightEdge);
Watch out: Defined after createEdgeSprites().
# topEdge
object 2D Game Lab
The invisible sprite at the top edge.
Type: Sprite
createEdgeSprites();
player.collide(topEdge);
Watch out: Defined after createEdgeSprites().
# bottomEdge
object 2D Game Lab
The invisible sprite at the bottom edge.
Type: Sprite
createEdgeSprites();
player.collide(bottomEdge);
Watch out: Defined after createEdgeSprites().
Sprite properties 32
# sprite.x
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game Lab
Degrees added to rotation each frame.
Type: number
fan.rotationSpeed = 5;
Watch out: It is per frame, not per second.
# sprite.depth
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game Lab-style
Alias of lifetime (p5.play name).
Type: number
spark.life = 30;
Watch out: Prefer lifetime.
# sprite.debug
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game Lab-style
Flips the sprite vertically when true (or -1).
Type: boolean
player.mirrorY = true;
Watch out: Assign to the property.
# sprite.animation
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game 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
property 2D Game Lab-style
Unique number of the sprite.
Type: number
print(player.id);
Watch out: Not reused.
Sprite methods 41
# sprite.setAnimation(label, animation?)
method 2D Game 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).
Name Type Required What it is labelstringyes Name of an animation animationAnimationoptional An 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)
method 2D Game Lab
Adds an animation to the sprite under a label. The first animation added is shown automatically.
Name Type Required What it is labelstringyes Name to use later animationAnimationyes Animation 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)
method 2D Game Lab-style
Adds a single image as a one-frame animation.
Name Type Required What it is labelstringyes Name imageImageyes Image 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)
method 2D Game Lab-style
Returns the animation stored under this label, or undefined.
Name Type Required What it is labelstringyes Name
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)
method 2D Game Lab
Switches to a previously added animation and rewinds it.
Name Type Required What it is labelstringyes Name 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?)
method 2D Game 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.
Name Type Required What it is typestringyes "rectangle", "circle" or "auto" (a box that hugs the visible pixels of the picture) offsetXnumberoptional Collider center offset from the sprite center offsetYnumberoptional Offset width_or_radiusnumberoptional Radius for "circle", width for "rectangle" heightnumberoptional Height 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?)
method 2D Game Lab
If the sprites overlap, pushes this sprite out of the target (and stops its motion into it). Returns true if they collided.
Name Type Required What it is targetSprite|Group|Nodeyes Sprite or group to collide with callbackfunctionoptional Called 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?)
method 2D Game Lab
Detects overlap without moving anything. Returns true when they overlap and calls the callback for each overlapping sprite.
Name Type Required What it is targetSprite|Group|Nodeyes Sprite or group callbackfunctionoptional Called 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?)
method 2D Game Lab
Both sprites bounce off each other like balls (uses mass and bounciness; immovable sprites do not move).
Name Type Required What it is targetSprite|Group|Nodeyes Sprite or group callbackfunctionoptional Called as callback(sprite, other)
Returns: boolean
ball.bounce(paddle);
Watch out: Immovable sprites are never pushed; set wall.immovable = true.
# sprite.bounceOff(target, callback?)
method 2D Game Lab
Game Lab name for bounce(): identical.
Name Type Required What it is targetSprite|Group|Nodeyes Sprite or group callbackfunctionoptional Called as callback(sprite, other)
Returns: boolean
ball.bounceOff(edges);
Watch out: Same as bounce.
# sprite.displace(target, callback?)
method 2D Game Lab
This sprite pushes the target out of the way (the opposite of collide).
Name Type Required What it is targetSprite|Group|Nodeyes Sprite or group callbackfunctionoptional Called as callback(sprite, other)
Returns: boolean
pusher.displace(boxes);
Watch out: Immovable targets are not moved.
# sprite.isTouching(target)
method 2D Game Lab
True if this sprite touches or overlaps the target (edges touching count).
Name Type Required What it is targetSprite|Group|Nodeyes Sprite 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)
method 2D Game Lab-style
Same as isTouching().
Name Type Required What it is targetSprite|Group|Nodeyes Sprite or group
Returns: boolean
if (player.isColliding(spikes)) { lives--; }
Watch out: See isTouching.
# sprite.isOverlapping(target)
method 2D Game Lab-style
True only if the sprites really overlap (not just touch).
Name Type Required What it is targetSprite|Group|Nodeyes Sprite or group
Returns: boolean
if (player.isOverlapping(zone)) { print("inside"); }
Watch out: Edges that only touch are not overlapping.
# sprite.touched(target)
method 2D VYOM
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).
Name Type Required What it is targetSprite|Group|Nodeyes Sprite 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?)
method 2D Game Lab-style
Sets velocityX/velocityY from a speed and a direction in degrees.
Name Type Required What it is speednumberyes Pixels per frame directionnumberoptional Degrees (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)
method 2D Game Lab
Game Lab name for setSpeed(speed, direction).
Name Type Required What it is speednumberyes Pixels per frame directionnumberyes Degrees
Returns: Sprite
ball.setSpeedAndDirection(4, 90);
Watch out: Direction 90 moves DOWN.
# sprite.setVelocity(vx, vy?)
method 2D Game Lab
Sets velocityX and velocityY at once.
Name Type Required What it is vxnumberyes Horizontal speed vynumberoptional Vertical speed
Returns: Sprite
ball.setVelocity(2, -3);
Watch out: Speeds are per frame.
# sprite.addSpeed(speed, direction)
method 2D Game Lab-style
Adds speed in a direction to the current velocity (an acceleration).
Name Type Required What it is speednumberyes Pixels per frame to add directionnumberyes Degrees
Returns: Sprite
rocket.addSpeed(0.2, 270);
Watch out: Keeps growing every call; use maxSpeed or limitSpeed to cap it.
# sprite.getSpeed()
method 2D Game Lab-style
Returns the current speed in pixels per frame.
No parameters.
Returns: number
print(ball.getSpeed());
Watch out: Always positive.
# sprite.getDirection()
method 2D Game 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)
method 2D Game Lab
Rotates the sprite so it points at a position (rotation in degrees).
Name Type Required What it is xnumberyes Target x ynumberyes Target 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)
method 2D Game Lab-style
Accelerates the sprite towards a point.
Name Type Required What it is forcenumberyes Speed added per frame xnumberyes Target x ynumberyes Target 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)
method 2D Game Lab-style
Scales the velocity down if the speed is above max.
Name Type Required What it is maxnumberyes Maximum speed
Returns: Sprite
bee.limitSpeed(5);
Watch out: One time check; call again after adding speed.
# sprite.destroy()
method 2D Game 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()
method 2D Game Lab-style
Same as destroy().
No parameters.
Returns: void
enemy.remove();
Watch out: See destroy.
# sprite.mouseIsOver()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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?)
method 2D Game Lab-style
Distance in pixels from this sprite to a point or another sprite.
Name Type Required What it is x_or_targetnumber|Spriteyes A number (then pass y too) or a sprite ynumberoptional y 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?)
method 2D Game Lab-style
Direction in degrees from this sprite to a point or sprite (0 = right, 90 = down). Handy with setSpeed().
Name Type Required What it is x_or_targetnumber|Spriteyes A number (then pass y too) or a sprite ynumberoptional y 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?)
method 2D Game 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.
Name Type Required What it is x_or_targetnumber|Spriteyes A number (then pass y and speed) or a sprite (then pass speed) y_or_speednumberyes y, or the speed when the first argument is a sprite speednumberoptional Pixels 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)
method 2D Game Lab-style
Puts the sprite at x, y.
Name Type Required What it is xnumberyes New x ynumberyes New y
Returns: Sprite
player.setPosition(200, 350);
Watch out: Same as setting x and y.
# sprite.setSize(width, height?)
method 2D Game Lab-style
Sets width and height.
Name Type Required What it is widthnumberyes New width heightnumberoptional New 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()
method 2D Game 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()
method 2D Game Lab-style
Makes the sprite visible again.
No parameters.
Returns: Sprite
secretDoor.show();
Watch out: Opposite of hide().
# sprite.isTouchingEdges()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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
property 2D Game 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)
method 2D Game Lab
Adds a sprite to the group (ignored if already inside).
Name Type Required What it is spriteSpriteyes Sprite to add
Returns: Group
enemies.add(enemy);
Watch out: Adding the same sprite twice does nothing.
# group.remove(sprite)
method 2D Game Lab
Removes the sprite from the group only (it is NOT destroyed). Returns true if it was in the group.
Name Type Required What it is spriteSpriteyes Sprite to remove
Returns: boolean
enemies.remove(enemy);
Watch out: Use sprite.destroy() to delete the sprite.
# group.contains(sprite)
method 2D Game Lab
True if the sprite is in the group.
Name Type Required What it is spriteSpriteyes Sprite to look for
Returns: boolean
if (enemies.contains(s)) { print("enemy"); }
Watch out: It checks identity, not position.
# group.get(index)
method 2D Game Lab
Returns the sprite at an index (same as group[index]).
Name Type Required What it is indexnumberyes 0-based index
Returns: Sprite
var first = enemies.get(0);
Watch out: Indexes start at 0; out of range gives undefined.
# group.toArray()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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)
method 2D Game Lab-style
Sets a property on every sprite.
Name Type Required What it is propertystringyes Property name valueanyyes Value to set
Returns: void
enemies.setPropertyEach("scale", 0.5);
Watch out: The property name is a string, with quotes.
# group.setVelocityEach(vx, vy?)
method 2D Game Lab
Sets the velocity of every sprite.
Name Type Required What it is vxnumberyes Horizontal speed vynumberoptional Vertical speed
Returns: void
enemies.setVelocityEach(0, 2);
Watch out: Speeds are per frame.
# group.setColorEach(color)
method 2D Game Lab
Sets shapeColor of every sprite.
Name Type Required What it is colorstringyes Color
Returns: void
coins.setColorEach("gold");
Watch out: Does nothing for sprites showing animations.
# group.setLifetimeEach(frames)
method 2D Game Lab
Sets lifetime of every sprite.
Name Type Required What it is framesnumberyes Frames to live
Returns: void
sparks.setLifetimeEach(30);
Watch out: Frames, not seconds.
# group.setAnimationEach(label, animation?)
method 2D Game Lab
Calls setAnimation on every sprite.
Name Type Required What it is labelstringyes Animation label animationAnimationoptional Optional 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()
method 2D Game Lab
Destroys every sprite in the group.
No parameters.
Returns: void
bullets.destroyEach();
Watch out: The group ends up empty.
# group.collide(target, callback?)
method 2D Game Lab
Runs sprite.collide(target) for every sprite in the group.
Name Type Required What it is targetSprite|Group|Nodeyes Target callbackfunctionoptional callback(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?)
method 2D Game Lab
Runs sprite.overlap(target) for every sprite.
Name Type Required What it is targetSprite|Group|Nodeyes Target callbackfunctionoptional callback(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?)
method 2D Game Lab
Runs sprite.bounce(target) for every sprite.
Name Type Required What it is targetSprite|Group|Nodeyes Target callbackfunctionoptional callback(sprite, other)
Returns: boolean
balls.bounce(balls);
Watch out: Bouncing a group off itself works, each pair is resolved.
# group.bounceOff(target, callback?)
method 2D Game Lab
Same as group.bounce().
Name Type Required What it is targetSprite|Group|Nodeyes Target callbackfunctionoptional callback(sprite, other)
Returns: boolean
balls.bounceOff(edges);
Watch out: See bounce.
# group.displace(target, callback?)
method 2D Game Lab
Runs sprite.displace(target) for every sprite.
Name Type Required What it is targetSprite|Group|Nodeyes Target callbackfunctionoptional callback(sprite, other)
Returns: boolean
pushers.displace(boxes);
Watch out: See sprite.displace.
# group.isTouching(target)
method 2D Game Lab
True if any sprite in the group touches the target.
Name Type Required What it is targetSprite|Group|Nodeyes Target
Returns: boolean
if (enemies.isTouching(player)) { gameOver(); }
Watch out: Touching is inclusive of edges.
# group.isColliding(target)
method 2D Game Lab-style
Same as isTouching.
Name Type Required What it is targetSprite|Group|Nodeyes Target
Returns: boolean
if (enemies.isColliding(player)) { gameOver(); }
Watch out: See isTouching.
# group.isOverlapping(target)
method 2D Game Lab-style
True if any sprite really overlaps the target.
Name Type Required What it is targetSprite|Group|Nodeyes Target
Returns: boolean
if (zone.isOverlapping(player)) { print("in"); }
Watch out: See sprite.isOverlapping.
# group.touched(target)
method 2D VYOM
True when any sprite of the group HAS touched the target before and none of them is touching it right now.
Name Type Required What it is targetSprite|Group|Nodeyes Target
Returns: boolean
if (enemies.touched(wall)) { print("an enemy reached the wall"); }
Watch out: Call it every frame. See sprite.touched.
# World.allSprites
property 2D Game 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)
method 2D Game Lab
Sets depth of every sprite (higher depth draws on top).
Name Type Required What it is depthnumberyes Depth
Returns: void
clouds.setDepthEach(-1);
Watch out: Depth is the draw order, not 3D depth.
# group.setRotationEach(degrees)
method 2D Game Lab
Sets rotation of every sprite.
Name Type Required What it is degreesnumberyes Rotation
Returns: void
arrows.setRotationEach(90);
Watch out: Degrees.
# group.setRotationSpeedEach(degrees)
method 2D Game Lab
Sets rotationSpeed of every sprite.
Name Type Required What it is degreesnumberyes Degrees per frame
Returns: void
stars.setRotationSpeedEach(3);
Watch out: Per frame.
# group.setScaleEach(scale)
method 2D Game Lab
Sets scale of every sprite.
Name Type Required What it is scalenumberyes Scale (1 = normal)
Returns: void
coins.setScaleEach(0.5);
Watch out: 1 is normal size.
# group.setVisibleEach(visible)
method 2D Game Lab
Shows or hides every sprite.
Name Type Required What it is visiblebooleanyes true or false
Returns: void
menuButtons.setVisibleEach(false);
Watch out: Hidden sprites still exist and collide.
# group.setSpeedAndDirectionEach(speed, direction?)
method 2D Game Lab
Calls setSpeed(speed, direction) on every sprite.
Name Type Required What it is speednumberyes Pixels per frame directionnumberoptional Degrees
Returns: void
bullets.setSpeedAndDirectionEach(6, 270);
Watch out: Direction 270 moves UP.
# group.isEmpty()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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()
method 2D Game 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?)
method 2D Game Lab-style
True if the mouse is over any sprite of the group.
Name Type Required What it is callbackfunctionoptional Called 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?)
method 2D Game Lab-style
True for the frame when any sprite of the group is clicked. The callback tells you which one.
Name Type Required What it is callbackfunctionoptional Called 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...)
function 2D Game 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.
Name Type Required What it is source...string|SpriteSheetyes File 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?)
function 2D Game 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).
Name Type Required What it is pathstringyes Image file frameWidthnumberyes Width of one frame frameHeightnumberyes Height of one frame countnumberoptional Number 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)
function 2D Game Lab
Loads an image for use with image() or sprite.addImage().
Name Type Required What it is pathstringyes Image 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
property 2D Game 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
property 2D Game 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
property 2D Game Lab
Hide the animation without hiding the sprite.
Type: boolean
run.visible = false;
Watch out: The sprite itself still collides.
# animation.scale
property 2D Game 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
property 2D Game 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
property 2D Game Lab-style
Horizontal drawing offset in pixels.
Type: number
run.offX = 5;
Watch out: Moves only the picture, not the collider.
# animation.offY
property 2D Game Lab-style
Vertical drawing offset in pixels.
Type: number
run.offY = -4;
Watch out: Moves only the picture, not the collider.
# animation.tint
property 2D Game 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()
method 2D Game Lab
Starts or resumes playing.
No parameters.
Returns: void
run.play();
Watch out: Animations play by default.
# animation.stop()
method 2D Game Lab
Pauses the animation on the current frame.
No parameters.
Returns: void
run.stop();
Watch out: It does not rewind; use rewind().
# animation.rewind()
method 2D Game Lab
Goes back to the first frame.
No parameters.
Returns: void
run.rewind();
Watch out: Does not change whether it is playing.
# animation.nextFrame()
method 2D Game 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()
method 2D Game Lab
Shows the previous frame.
No parameters.
Returns: void
run.previousFrame();
Watch out: Wraps only if looping.
# animation.changeFrame(frame)
method 2D Game Lab
Jumps to a frame number (clamped).
Name Type Required What it is framenumberyes Frame index
Returns: void
run.changeFrame(2);
Watch out: The first frame is 0.
# animation.getFrame()
method 2D Game Lab
Returns the current frame number.
No parameters.
Returns: number
print(run.getFrame());
Watch out: Starts at 0.
# animation.getFrameCount()
method 2D Game 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()
method 2D Game Lab
Width of the current frame in pixels.
No parameters.
Returns: number
print(run.getWidth());
Watch out: Frame size, before scaling.
# animation.getHeight()
method 2D Game Lab
Height of the current frame in pixels.
No parameters.
Returns: number
print(run.getHeight());
Watch out: Frame size, before scaling.
# animation.isPlaying()
method 2D Game 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()
method 2D Game 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?)
method 2D Game Lab-style
Draws the current frame at a position (for animations that are not on a sprite). Also advances nothing: call nextFrame yourself.
Name Type Required What it is xnumberyes Center x ynumberyes Center y rotationnumberoptional Degrees
Returns: void
run.draw(100, 100);
Watch out: Sprites advance their own animation automatically; plain drawing does not.
Camera & World 21
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
property 2D Game 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
property 2D Game 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
property 2D Game Lab
Camera zoom (1 = normal, 2 = twice as close).
Type: number
camera.zoom = 2;
Watch out: Zoom 0 or negative is invalid.
# camera.position
property 2D Game 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()
method 2D Game 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()
method 2D Game 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?)
method 2D Game Lab-style
Makes the camera follow a sprite every frame.
Name Type Required What it is spriteSpriteyes Sprite to follow smoothingnumberoptional 0.001 to 1 (1 = snap, small = smooth)
Returns: void
camera.follow(player, 0.1);
Watch out: Pass null to stop following.
# camera.mouseX
property 2D Game 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
property 2D Game Lab
Mouse y position in world coordinates.
Type: number read-only
target.y = camera.mouseY;
Watch out: World.mouseY / mouseY are screen coordinates.
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
property 2D Game 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
property 2D Game Lab
Height of the game screen in pixels.
Type: number read-only
ball.y = World.height / 2;
Watch out: See width.
# World.frameCount
property 2D Game 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
property 2D Game Lab
Whole seconds since the game started.
Type: number read-only
text("Time: " + World.seconds, 10, 20);
Watch out: Rounded down.
# World.frameRate
property 2D Game 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
property 2D Game 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
property 2D Game Lab
Mouse x in screen coordinates.
Type: number read-only
print(World.mouseX);
Watch out: Same as the global mouseX.
# World.mouseY
property 2D Game Lab
Mouse y in screen coordinates.
Type: number read-only
print(World.mouseY);
Watch out: Same as the global mouseY.
# World.camera
property 2D Game 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)
function 2D Game Lab
Sets the frame rate of update()/draw(). Same as World.frameRate = fps.
Name Type Required What it is fpsnumberyes Frames per second
Returns: void
frameRate(60);
Watch out: It is a function here; World.frameRate is a property.
Drawing 41
# background(color)
function 2D Game Lab
Fills the whole screen with a color. Call it first in draw() to erase the previous frame.
Name Type Required What it is colorstring|numberyes A 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()
function 2D Game 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)
function 2D Game Lab
Sets the fill color for the shapes and text drawn afterwards.
Name Type Required What it is colorstring|numberyes Color, 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()
function 2D Game 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)
function 2D Game Lab
Sets the outline color.
Name Type Required What it is colorstring|numberyes Outline 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()
function 2D Game 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)
function 2D Game Lab
Sets the outline thickness.
Name Type Required What it is weightnumberyes Outline thickness in pixels
Returns: void
strokeWeight(4);
Watch out: Also controls line() thickness.
# rect(x, y, width, height?)
function 2D Game Lab
Draws a rectangle.
Name Type Required What it is xnumberyes Left (or center, see rectMode) ynumberyes Top widthnumberyes Width heightnumberoptional Height (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?)
function 2D Game Lab
Draws an ellipse (or circle).
Name Type Required What it is xnumberyes Center x ynumberyes Center y widthnumberyes Width heightnumberoptional Height (default = width)
Returns: void
ellipse(200, 200, 100, 60);
Watch out: x,y is the center by default.
# circle(x, y, diameter)
function 2D Game Lab
Draws a circle. The third value is the DIAMETER, not the radius.
Name Type Required What it is xnumberyes Center x ynumberyes Center y diameternumberyes Diameter
Returns: void
circle(200, 200, 50);
Watch out: Diameter, not radius.
# line(x1, y1, x2, y2)
function 2D Game Lab
Draws a line.
Name Type Required What it is x1numberyes Start x y1numberyes Start y x2numberyes End x y2numberyes End y
Returns: void
stroke("white");
line(0, 0, 400, 400);
Watch out: Uses the stroke color; with noStroke() nothing appears.
# point(x, y)
function 2D Game Lab
Draws a single point.
Name Type Required What it is xnumberyes x ynumberyes y
Returns: void
stroke("yellow");
strokeWeight(5);
point(100, 100);
Watch out: Make it visible with strokeWeight().
# triangle(x1, y1, x2, y2, x3, y3)
function 2D Game Lab
Draws a triangle from three corners.
Name Type Required What it is x1numberyes x1 y1numberyes y1 x2numberyes x2 y2numberyes y2 x3numberyes x3 y3numberyes y3
Returns: void
triangle(200, 50, 150, 150, 250, 150);
Watch out: Corner order does not matter.
# arc(x, y, width, height, start, stop)
function 2D Game Lab
Draws part of an ellipse between two angles (degrees unless angleMode(RADIANS)).
Name Type Required What it is xnumberyes Center x ynumberyes Center y widthnumberyes Width heightnumberyes Height startnumberyes Start angle stopnumberyes Stop angle
Returns: void
arc(200, 200, 100, 100, 0, 270);
Watch out: Angles go clockwise starting at 3 o'clock.
# text(value, x, y)
function 2D Game Lab
Draws text. Uses the fill color and textSize().
Name Type Required What it is valueanyyes Text or number to show xnumberyes x ynumberyes y
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)
function 2D Game Lab
Sets the text size.
Name Type Required What it is sizenumberyes Font size in pixels
Returns: void
textSize(24);
Watch out: Stays until changed.
# textAlign(horizontal, vertical?)
function 2D Game Lab
Sets how text is positioned around x,y.
Name Type Required What it is horizontalstringyes LEFT, CENTER or RIGHT verticalstringoptional TOP, 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?)
function 2D Game Lab
Draws an image (top-left corner at x,y unless imageMode changed).
Name Type Required What it is imgImage|Animationyes Image from loadImage() xnumberyes x ynumberyes y widthnumberoptional Draw width heightnumberoptional Draw height
Returns: void
image(bg, 0, 0, 400, 400);
Watch out: Load images once with loadImage(), not every frame.
# imageMode(mode)
function 2D Game Lab
Chooses whether image() x,y is the corner or the center.
Name Type Required What it is modestringyes CORNER or CENTER
Returns: void
imageMode(CENTER);
Watch out: Use the constants without quotes.
# rectMode(mode)
function 2D Game Lab
Chooses how rect() reads its arguments.
Name Type Required What it is modestringyes CORNER, CENTER, CORNERS or RADIUS
Returns: void
rectMode(CENTER);
rect(200, 200, 50, 50);
Watch out: Stays until changed.
# ellipseMode(mode)
function 2D Game Lab
Chooses how ellipse() reads its arguments.
Name Type Required What it is modestringyes CENTER, CORNER, CORNERS or RADIUS
Returns: void
ellipseMode(CORNER);
Watch out: Stays until changed.
# push()
function 2D Game 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()
function 2D Game Lab
Restores the style and transform saved by push().
No parameters.
Returns: void
pop();
Watch out: Needs a matching push().
# translate(x, y)
function 2D Game Lab-style
Moves the drawing origin.
Name Type Required What it is xnumberyes Move right ynumberyes Move down
Returns: void
translate(200, 200);
rect(0, 0, 40, 40);
Watch out: Affects everything drawn afterwards; wrap in push()/pop().
# rotate(angle)
function 2D Game Lab-style
Rotates the drawing (degrees unless angleMode(RADIANS)).
Name Type Required What it is anglenumberyes Degrees
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?)
function 2D Game Lab-style
Scales the drawing.
Name Type Required What it is xnumberyes Horizontal factor ynumberoptional Vertical factor (default = x)
Returns: void
push();
scale(2);
rect(10, 10, 20, 20);
pop();
Watch out: Also scales line thickness.
# CENTER
constant 2D Game Lab
Constant for centered drawing/alignment.
Type: string
rectMode(CENTER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# CORNER
constant 2D Game Lab
Constant: x,y is the top-left corner.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# CORNERS
constant 2D Game Lab
Constant: two opposite corners are given.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# RADIUS
constant 2D Game Lab
Constant: width and height are radii.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
Constant for left text alignment.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# RIGHT
constant 2D Game Lab
Constant for right text alignment.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
Constant for top vertical alignment.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# BOTTOM
constant 2D Game Lab
Constant for bottom vertical alignment.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# BASELINE
constant 2D Game Lab
Constant for baseline vertical alignment (default).
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# DEGREES
constant 2D Game Lab
Constant for angleMode(DEGREES), the default.
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
# RADIANS
constant 2D Game Lab
Constant for angleMode(RADIANS).
Type: string
rectMode(CORNER);
Watch out: Write the constants without quotes (CENTER, not "CENTER").
The number pi (3.14159...).
Type: number
var c = 2 * PI * 10;
Watch out: Use the constant, not 3.14.
# TWO_PI
constant 2D + 3D Game Lab
2 * pi.
Type: number
var full = TWO_PI;
Watch out: Angles in Nova default to degrees.
# HALF_PI
constant 2D + 3D Game Lab
pi / 2.
Type: number
var q = HALF_PI;
Watch out: See PI.
# QUARTER_PI
constant 2D + 3D Game Lab
pi / 4.
Type: number
var q = QUARTER_PI;
Watch out: See PI.
Input 20
# keyDown(key)
function 2D + 3D Game Lab
True every frame while the key is held down.
Name Type Required What it is keystringyes Key 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)
function 2D + 3D Game Lab
True for exactly one frame when the key is pressed.
Name Type Required What it is keystringyes Key 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)
function 2D + 3D Game Lab
True for exactly one frame when the key is released.
Name Type Required What it is keystringyes Key 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?)
function 2D + 3D Game Lab
True while the mouse button is held.
Name Type Required What it is buttonstringoptional "left" (default), "right" or "middle"
Returns: boolean
if (mouseDown("left")) { ball.x = mouseX; }
Watch out: Use quotes: "left".
# mouseWentDown(button?)
function 2D + 3D Game Lab
True for one frame when the button is pressed.
Name Type Required What 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?)
function 2D + 3D Game Lab
True for one frame when the button is released.
Name Type Required What it is buttonstringoptional "left" (default), "right" or "middle"
Returns: boolean
if (mouseWentUp("left")) { print("up"); }
Watch out: One frame only.
# mouseIsPressed()
function 2D + 3D Game 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)
function 2D Game Lab
True if the mouse pointer is over the sprite.
Name Type Required What it is spriteSprite|Nodeyes Sprite 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)
function 2D Game Lab
True for the one frame in which the left button is pressed while the pointer is over the sprite.
Name Type Required What it is spriteSprite|Nodeyes Sprite 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
object 2D + 3D Game 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
object 2D + 3D Game Lab
Current mouse y in screen coordinates.
Type: number read-only
player.y = mouseY;
Watch out: See mouseX.
# pmouseX
object 2D + 3D Game Lab
Mouse x in the previous frame.
Type: number read-only
var dx = mouseX - pmouseX;
Watch out: Equals mouseX on the first frame.
# pmouseY
object 2D + 3D Game Lab
Mouse y in the previous frame.
Type: number read-only
var dy = mouseY - pmouseY;
Watch out: See pmouseX.
# mouseDeltaX()
function 2D + 3D VYOM
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()
function 2D + 3D VYOM
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?)
function 2D + 3D VYOM
Locks and hides the mouse pointer so you can read unlimited mouse movement with mouseDeltaX()/mouseDeltaY() (first-person look). Pass false to release it.
Name Type Required What it is onbooleanoptional true 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()
function 2D + 3D Game 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()
function 2D + 3D VYOM
True while any keyboard key is held.
No parameters.
Returns: boolean
if (anyKeyDown()) { print("typing"); }
Watch out: Mouse buttons are not keys.
# anyKeyWentDown()
function 2D + 3D VYOM
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)
function 2D VYOM
Returns the front-most visible sprite under a point, or undefined. Use it to find what was clicked.
Name Type Required What it is xnumberyes x position ynumberyes y 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() 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.
Name Type Required What it is anumber|Arrayoptional Max, or min; or an array to pick from bnumberoptional Max 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)
function 2D + 3D Game Lab
Random WHOLE number from min to max, both included. (Game Lab's main random function.)
Name Type Required What it is minnumberyes Lowest whole number maxnumberyes Highest whole number
Returns: number
var dice = randomNumber(1, 6);
Watch out: Both ends can be returned.
# randomChoice(array)
function 2D + 3D VYOM
Returns a random element of an array.
Name Type Required What it is arrayArrayyes Array to pick from
Returns: any
var enemyColor = randomChoice(["red", "blue"]);
Watch out: The array must not be empty.
# rgb(r, g, b)
function 2D + 3D Game Lab
Makes a color string.
Name Type Required What it is rnumberyes 0-255 gnumberyes 0-255 bnumberyes 0-255
Returns: string
fill(rgb(255, 128, 0));
Watch out: Returns a string like "rgb(255,128,0)".
# rgba(r, g, b, a)
function 2D + 3D Game Lab
Makes a color string with opacity.
Name Type Required What it is rnumberyes 0-255 gnumberyes 0-255 bnumberyes 0-255 anumberyes 0-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)
function 2D + 3D Game Lab
Re-maps a number from one range to another.
Name Type Required What it is valuenumberyes Value to convert start1numberyes Input range start stop1numberyes Input range end start2numberyes Output range start stop2numberyes Output 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)
function 2D + 3D Game Lab
Distance between two points.
Name Type Required What it is x1numberyes x1 y1numberyes y1 x2numberyes x2 y2numberyes y2
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)
function 2D + 3D Game Lab
Keeps a number between low and high.
Name Type Required What it is valuenumberyes Value lownumberyes Minimum highnumberyes Maximum
Returns: number
player.x = constrain(player.x, 20, 380);
Watch out: Order is (value, low, high).
# lerp(a, b, t)
function 2D + 3D Game Lab
Linear interpolation between a and b.
Name Type Required What it is anumberyes Start bnumberyes End tnumberyes 0 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)
function 2D + 3D Game Lab
Rounds to the nearest whole number.
Name Type Required What it is valuenumberyes Number
Returns: number
var n = round(2.6);
Watch out: Halves round up.
# floor(value)
function 2D + 3D Game Lab
Rounds down.
Name Type Required What it is valuenumberyes Number
Returns: number
var n = floor(2.9);
Watch out: Negative numbers round toward minus infinity.
# ceil(value)
function 2D + 3D Game Lab
Rounds up.
Name Type Required What it is valuenumberyes Number
Returns: number
var n = ceil(2.1);
Watch out: Negative numbers round toward zero.
# abs(value)
function 2D + 3D Game Lab
Absolute value (without the minus sign).
Name Type Required What it is valuenumberyes Number
Returns: number
var d = abs(a - b);
Watch out: Never negative.
# sqrt(value)
function 2D + 3D Game Lab
Square root.
Name Type Required What it is valuenumberyes Number
Returns: number
var r = sqrt(16);
Watch out: NaN for negative numbers.
# pow(base, exponent)
function 2D + 3D Game Lab
base to the power of exponent.
Name Type Required What it is basenumberyes Base exponentnumberyes Exponent
Returns: number
var s = pow(2, 8);
Watch out: Order is (base, exponent).
# sin(angle)
function 2D + 3D Game Lab
Sine of an angle. Angles are in degrees by default like in Game Lab.
Name Type Required What it is anglenumberyes Degrees (RADIANS after angleMode(RADIANS))
Returns: number
var h = sin(30);
Watch out: JavaScript's Math.sin uses radians; this one uses degrees.
# cos(angle)
function 2D + 3D Game Lab
Cosine of an angle in degrees.
Name Type Required What it is anglenumberyes Degrees
Returns: number
var w = cos(60);
Watch out: Degrees by default.
# tan(angle)
function 2D + 3D Game Lab
Tangent of an angle in degrees.
Name Type Required What it is anglenumberyes Degrees
Returns: number
var t = tan(45);
Watch out: Degrees by default.
# asin(value)
function 2D + 3D Game Lab
Arc sine, returned in degrees.
Name Type Required What it is valuenumberyes -1 to 1
Returns: number
var a = asin(0.5);
Watch out: Result unit follows angleMode.
# acos(value)
function 2D + 3D Game Lab
Arc cosine, returned in degrees.
Name Type Required What it is valuenumberyes -1 to 1
Returns: number
var a = acos(0.5);
Watch out: Result unit follows angleMode.
# atan(value)
function 2D + 3D Game Lab
Arc tangent, returned in degrees.
Name Type Required What it is valuenumberyes Number
Returns: number
var a = atan(1);
Watch out: Use atan2 for directions.
# atan2(y, x)
function 2D + 3D Game Lab
Angle of the vector (x, y) in degrees. Note that y comes first.
Name Type Required What it is ynumberyes y difference xnumberyes x difference
Returns: number
var angle = atan2(mouseY - player.y, mouseX - player.x);
Watch out: The order is (y, x).
# degrees(radians)
function 2D + 3D Game Lab
Converts radians to degrees.
Name Type Required What it is radiansnumberyes Angle in radians
Returns: number
var d = degrees(PI);
Watch out: Not affected by angleMode.
# radians(degrees)
function 2D + 3D Game Lab
Converts degrees to radians.
Name Type Required What it is degreesnumberyes Angle in degrees
Returns: number
var r = radians(180);
Watch out: Not affected by angleMode.
# min(values...)
function 2D + 3D Game Lab
Smallest of the numbers.
Name Type Required What it is values...numberyes Numbers
Returns: number
var m = min(a, b, c);
Watch out: With an empty call the result is Infinity.
# max(values...)
function 2D + 3D Game Lab
Largest of the numbers.
Name Type Required What it is values...numberyes Numbers
Returns: number
var m = max(a, b, c);
Watch out: With an empty call the result is -Infinity.
# sq(value)
function 2D + 3D Game Lab
Square of a number.
Name Type Required What it is valuenumberyes Number
Returns: number
var a = sq(5);
Watch out: Same as value * value.
# log(value)
function 2D + 3D Game Lab
Natural logarithm.
Name Type Required What it is valuenumberyes Number
Returns: number
var l = log(10);
Watch out: Natural log (base e), not base 10.
# exp(value)
function 2D + 3D Game Lab
e raised to the power.
Name Type Required What it is valuenumberyes Exponent
Returns: number
var e1 = exp(1);
Watch out: e is about 2.718.
# mag(x, y)
function 2D + 3D Game Lab
Length of the vector (x, y).
Name Type Required What it is xnumberyes x ynumberyes y
Returns: number
var speed = mag(vx, vy);
Watch out: Two numbers.
# norm(value, start, stop)
function 2D + 3D Game Lab
Converts a value in a range to 0..1.
Name Type Required What it is valuenumberyes Value startnumberyes Range start stopnumberyes Range end
Returns: number
var t = norm(mouseX, 0, 400);
Watch out: Not limited to 0..1.
# angleMode(mode)
function 2D + 3D Game Lab
Chooses whether sin/cos/tan/rotate use degrees (default) or radians.
Name Type Required What it is modestringyes DEGREES or RADIANS
Returns: void
angleMode(RADIANS);
Watch out: Affects all angle functions from then on.
# shuffle(array)
function 2D + 3D VYOM
Returns a new array with the same items in random order (the original is not changed).
Name Type Required What it is arrayArrayyes Array 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)
function 2D + 3D VYOM
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.
Name Type Required What it is pathstringyes Node 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)
function 2D + 3D VYOM
Searches the whole scene tree for a node with this name.
Name Type Required What it is namestringyes Node 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)
function 2D + 3D VYOM
Returns all nodes that belong to a Godot group.
Name Type Required What it is groupstringyes Group 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)
function 3D VYOM
Like getNode() but guarantees a 3D reference with position/rotation/scale and 3D movement methods.
Name Type Required What it is pathstringyes Node 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)
function 3D VYOM
Searches the scene for a 3D node by name.
Name Type Required What it is namestringyes Node 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?)
function 3D VYOM
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.
Name Type Required What it is typestringyes "box", "sphere", "capsule", "cylinder", "plane", "light" or "camera" xnumberoptional X position ynumberoptional Y position znumberoptional Z 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?)
function 3D VYOM
Instances a scene (as made in the editor) into the running game and places it. The scene's own script, if any, runs.
Name Type Required What it is scenestringyes Path of a .tscn scene, e.g. "res://scenes/enemy.tscn" positionVec3|number[]optional Where 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)
function 3D VYOM
Removes a node (and its children) from the running scene.
Name Type Required What it is nodeNodeRefyes Node 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?)
function 3D VYOM
Casts a ray through the physics world and reports the first collider it hits.
Name Type Required What it is originVec3yes Start point directionVec3yes Direction (does not need to be normalized) distancenumberoptional Maximum 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
property 2D + 3D VYOM
Path of the node in the scene.
Type: string
print(boss.path);
Watch out: Read-only.
# node.name
property 2D + 3D VYOM
Name of the node.
Type: string
print(boss.name);
Watch out: Read-only; rename in the editor.
# node.type
property 2D + 3D VYOM
Godot class of the node, e.g. "CharacterBody3D".
Type: string
if (n.type === "Area3D") { }
Watch out: Read-only.
# node.visible
property 2D + 3D VYOM
Shows or hides the node (and children).
Type: boolean
ghost.visible = false;
Watch out: Hidden physics bodies still collide.
# node.isValid()
method 2D + 3D VYOM
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)
method 2D + 3D VYOM
Reads any Godot property of the node, e.g. "modulate" or "mass".
Name Type Required What it is namestringyes Godot property name
Returns: any
var m = crate.getProperty("mass");
Watch out: Property names are Godot's (snake_case): "collision_layer".
# node.setProperty(name, value)
method 2D + 3D VYOM
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.
Name Type Required What it is namestringyes Godot property name valueanyyes New value
Returns: void
crate.setProperty("mass", 5);
Watch out: Wrong names are reported as warnings in the Output.
# node.call(method, args...)
method 2D + 3D VYOM
Calls a Godot method on the node.
Name Type Required What it is methodstringyes Godot method name args...anyyes Arguments
Returns: any
player.call("play", "walk");
Watch out: Use Godot's method names (snake_case).
# node.destroy()
method 2D + 3D VYOM
Removes the node from the scene.
No parameters.
Returns: void
coin.destroy();
Watch out: The reference becomes invalid.
# node.remove()
method 2D + 3D VYOM
Same as destroy().
No parameters.
Returns: void
coin.remove();
Watch out: See destroy.
# node.getParent()
method 2D + 3D VYOM
Returns the parent node.
No parameters.
Returns: NodeRef
var p = child.getParent();
Watch out: Returns null for the root.
# node.getChildren()
method 2D + 3D VYOM
Returns the child nodes.
No parameters.
Returns: NodeRef[]
var kids = enemies.getChildren();
Watch out: Direct children only.
# node.findChild(name)
method 2D + 3D VYOM
Searches the descendants for a node by name.
Name Type Required What it is namestringyes Child name
Returns: NodeRef
var gun = player.findChild("Gun");
Watch out: Returns null if there is none.
# node.isInGroup(group)
method 2D + 3D VYOM
True if the node is in the group.
Name Type Required What it is groupstringyes Group name
Returns: boolean
if (other.isInGroup("enemies")) { }
Watch out: Group names are case sensitive.
# node.addToGroup(group)
method 2D + 3D VYOM
Adds the node to a group.
Name Type Required What it is groupstringyes Group name
Returns: void
crate.addToGroup("pickups");
Watch out: Groups added at run time are not saved to the scene.
# node.equals(other)
method 2D + 3D VYOM
True if both references point to the same node.
Name Type Required What it is otherNodeRefyes Other reference
Returns: boolean
if (other.equals(player)) { }
Watch out: Use it instead of === (two references to one node are different objects).
Horizontal position (2D).
Type: number
node.x += 2;
Watch out: Y points down.
Vertical position (2D).
Type: number
node.y += 2;
Watch out: Y points down.
# node.position
property 2D VYOM
Position as {x, y} (2D).
Type: object
node.position = {x: 10, y: 20};
Watch out: Assign a whole object to change it.
# node.rotation
property 2D VYOM
Rotation in degrees (2D).
Type: number
node.rotation = 90;
Watch out: Degrees, not radians.
# node.scaleX
property 2D VYOM
Horizontal scale (2D).
Type: number
node.scaleX = 2;
Watch out: 1 is normal.
# node.scaleY
property 2D VYOM
Vertical scale (2D).
Type: number
node.scaleY = 2;
Watch out: 1 is normal.
# node.setScale(x, y?)
method 2D VYOM
Sets both scale components.
Name Type Required What it is xnumberyes Horizontal scale ynumberoptional Vertical scale (default = x)
Returns: void
node.setScale(2);
Watch out: 1 is normal size.
# node.zIndex
property 2D VYOM
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
property 2D + 3D VYOM
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
property 2D + 3D VYOM
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
property 3D VYOM
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?)
method 2D + 3D VYOM
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).
Name Type Required What it is vxnumberyes Horizontal speed vynumberyes Vertical speed vznumberoptional Depth speed (3D only)
Returns: void
player.setVelocity(4, 0);
Watch out: Same units as velocityX / velocityY / velocityZ.
# node.isTouching(target)
method 2D VYOM
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.
Name Type Required What it is targetNodeRef|Sprite|Groupyes A 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)
method 2D VYOM
Same as isTouching().
Name Type Required What it is targetNodeRef|Sprite|Groupyes Target
Returns: boolean
if (player.isColliding(spike)) { print("ouch"); }
Watch out: See isTouching.
# node.isOverlapping(target)
method 2D VYOM
True only if the boxes really overlap (just touching edges does not count).
Name Type Required What it is targetNodeRef|Sprite|Groupyes Target
Returns: boolean
if (player.isOverlapping(zone)) { print("inside"); }
Watch out: See isTouching.
# node.touched(target)
method 2D VYOM
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).
Name Type Required What it is targetNodeRef|Sprite|Groupyes Target
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()
method 2D VYOM
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()
method 2D VYOM
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()
method 2D VYOM
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()
method 2D VYOM
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?)
method 2D VYOM
Distance in pixels from this node to a point, node or sprite.
Name Type Required What it is x_or_targetnumber|NodeRef|Spriteyes A number (then pass y too), a node or a sprite ynumberoptional y 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?)
method 2D VYOM
Direction in degrees from this node to a point or node (0 = right, 90 = down).
Name Type Required What it is x_or_targetnumber|NodeRef|Spriteyes A number (then pass y too), a node or a sprite ynumberoptional y 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?)
method 2D VYOM
Moves the node straight towards a point or node by at most speed pixels, never overshooting. Returns true when it arrived.
Name Type Required What it is x_or_targetnumber|NodeRef|Spriteyes A number (then pass y and speed), a node or a sprite (then pass speed) y_or_speednumberyes y, or the speed when the first argument is a node speednumberoptional Pixels 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)
method 2D VYOM
Puts the node at x, y.
Name Type Required What it is xnumberyes New x ynumberyes New y
Returns: Node2D
player.setPosition(100, 200);
Watch out: Same as setting x and y.
# node.hide()
method 2D VYOM
Hides the node (visible = false).
No parameters.
Returns: Node2D
coin.hide();
Watch out: Hidden physics bodies still collide.
# node.show()
method 2D VYOM
Shows the node again.
No parameters.
Returns: Node2D
coin.show();
Watch out: Opposite of hide().
Vectors 15
# vec3(x?, y?, z?)
function 3D VYOM
Creates a 3D vector. Also accepts an array [x, y, z] or another vector.
Name Type Required What it is xnumberoptional X (default 0) ynumberoptional Y (default 0) znumberoptional Z (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.
X component.
Type: number
v.x = 5;
Watch out: Positive x is right.
Y component.
Type: number
v.y = 5;
Watch out: Positive y is up.
Z component.
Type: number
v.z = -5;
Watch out: Negative z is forward (away from the default camera).
Returns this + v. Does not change this vector.
Name Type Required What it is vVec3yes Other vector
Returns: Vec3
var p = a.add(b);
Watch out: Returns a NEW vector; a is unchanged.
Returns this - v.
Name Type Required What it is vVec3yes Other vector
Returns: Vec3
var d = target.sub(me);
Watch out: Returns a new vector.
Returns this multiplied by a number.
Name Type Required What it is snumberyes Factor
Returns: Vec3
var big = v.scale(2);
Watch out: Returns a new vector.
Length of the vector.
No parameters.
Returns: number
var d = v.length();
Watch out: It is a method: call it with ().
# v.normalize()
method 3D VYOM
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.
Dot product.
Name Type Required What it is vVec3yes Other vector
Returns: number
var facing = forward.dot(toEnemy);
Watch out: Result is a number, not a vector.
Cross product.
Name Type Required What it is vVec3yes Other vector
Returns: Vec3
var side = forward.cross(up);
Watch out: Order matters (a x b = -(b x a)).
# v.distanceTo(v)
method 3D VYOM
Distance to another point.
Name Type Required What it is vVec3yes Other point
Returns: number
if (me.distanceTo(enemy) < 5) { flee(); }
Watch out: Both must be Vec3s.
# v.lerp(v, t)
method 3D VYOM
Linear interpolation towards v.
Name Type Required What it is vVec3yes Target tnumberyes 0 to 1
Returns: Vec3
var p = a.lerp(b, 0.5);
Watch out: t = 0 returns this, t = 1 returns v.
# v.toArray()
method 3D VYOM
Returns [x, y, z].
No parameters.
Returns: number[]
var arr = v.toArray();
Watch out: Copy, not a reference.
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
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?)
function 3D VYOM
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.
Name Type Required What it is xnumber|Vec3yes X or a vector ynumberoptional Y znumberoptional Z
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?)
function 3D VYOM
Rotates the node (degrees per second, multiplied by dt).
Name Type Required What it is xnumber|Vec3yes Degrees around X ynumberoptional Degrees around Y znumberoptional Degrees around Z
Returns: void
rotate3D(0, 90, 0); // spin once per 4 seconds
Watch out: Degrees per second, not per frame.
# lookAt3D(target)
function 3D VYOM
Turns the node so its -Z axis points at the target.
Name Type Required What it is targetVec3|NodeRefyes Point or node to face
Returns: void
lookAt3D(getNode3D("Player").position);
Watch out: The node must not be exactly above/below the target.
# getPosition3D()
function 3D VYOM
Returns the global position.
No parameters.
Returns: Vec3
var p = getPosition3D();
Watch out: A copy: change it with setPosition3D().
# setPosition3D(x, y?, z?)
function 3D VYOM
Sets the global position.
Name Type Required What it is xnumber|Vec3yes X or a vector ynumberoptional Y znumberoptional Z
Returns: void
setPosition3D(0, 5, 0);
Watch out: Teleports; physics bodies keep their velocity.
# getRotation3D()
function 3D VYOM
Returns the rotation in degrees (x, y, z).
No parameters.
Returns: Vec3
var r = getRotation3D();
Watch out: Degrees, not radians.
# setRotation3D(x, y?, z?)
function 3D VYOM
Sets the rotation in degrees.
Name Type Required What it is xnumber|Vec3yes Degrees X or a vector ynumberoptional Degrees Y znumberoptional Degrees Z
Returns: void
setRotation3D(0, 90, 0);
Watch out: Degrees.
# setScale3D(x, y?, z?)
function 3D VYOM
Sets the scale.
Name Type Required What it is xnumber|Vec3yes X or a vector (one number scales all axes) ynumberoptional Y znumberoptional Z
Returns: void
setScale3D(2);
Watch out: Scaling a physics body also scales its collision shape.
# setVelocity3D(x, y?, z?)
function 3D VYOM
Sets the velocity of a CharacterBody3D (metres per second).
Name Type Required What it is xnumber|Vec3yes X or a vector ynumberoptional Y znumberoptional Z
Returns: void
setVelocity3D(0, 8, 0); // jump
Watch out: Only CharacterBody3D / RigidBody3D have a velocity.
# moveAndSlide3D()
function 3D VYOM
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()
function 3D VYOM
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()
function 3D VYOM
True if the body collided during the last moveAndSlide3D().
No parameters.
Returns: boolean
if (isColliding3D()) { print("bump"); }
Watch out: Needs moveAndSlide3D().
# playAnimation3D(name)
function 3D VYOM
Plays an animation of the first AnimationPlayer found in the node (e.g. from an imported model).
Name Type Required What it is namestringyes Animation name from the node's AnimationPlayer
Returns: void
playAnimation3D("run");
Watch out: The animation must exist in the AnimationPlayer; check the Animation panel.
# stopAnimation3D()
function 3D VYOM
Stops the current animation.
No parameters.
Returns: void
stopAnimation3D();
Watch out: No-op if nothing plays.
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.
The project's 3D gravity (default 9.8).
Type: number
velocity3D.y -= gravity3D * dt;
Watch out: Read-only.
# node.position
property 3D VYOM
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
property 3D VYOM
Rotation in degrees.
Type: Vec3
enemy.rotation = vec3(0, 90, 0);
Watch out: Degrees.
# node.scale
property 3D VYOM
Scale.
Type: Vec3
enemy.scale = vec3(2, 2, 2);
Watch out: 1 is normal.
# node.velocity
property 3D VYOM
Velocity of a CharacterBody3D / RigidBody3D.
Type: Vec3
enemy.velocity = vec3(0, 5, 0);
Watch out: Metres per second.
# node.getVelocity3D()
method 3D VYOM
Returns the velocity.
No parameters.
Returns: Vec3
var v = enemy.getVelocity3D();
Watch out: A copy.
# node.move3D(x, y?, z?)
method 3D VYOM
Moves the referenced node (see move3D).
Name Type Required What it is xnumber|Vec3yes X or vector ynumberoptional znumberoptional
Returns: void
enemy.move3D(0, 0, -3);
Watch out: Per second.
# node.rotate3D(x, y?, z?)
method 3D VYOM
Rotates the referenced node.
Name Type Required What it is xnumber|Vec3yes X or vector ynumberoptional znumberoptional
Returns: void
enemy.rotate3D(0, 45, 0);
Watch out: Degrees per second.
# node.lookAt3D(target)
method 3D VYOM
Makes the referenced node face a target.
Name Type Required What it is targetVec3|NodeRefyes Point or node to face
Returns: void
enemy.lookAt3D(player);
Watch out: See lookAt3D.
# node.getPosition3D()
method 3D VYOM
Position.
No parameters.
Returns: Vec3
var p = enemy.getPosition3D();
Watch out: Copy.
# node.setPosition3D(x, y?, z?)
method 3D VYOM
Sets the position.
Name Type Required What it is xnumber|Vec3yes ynumberoptional znumberoptional
Returns: void
enemy.setPosition3D(1, 2, 3);
Watch out: Teleports.
# node.getRotation3D()
method 3D VYOM
Rotation in degrees.
No parameters.
Returns: Vec3
var r = enemy.getRotation3D();
Watch out: Degrees.
# node.setRotation3D(x, y?, z?)
method 3D VYOM
Sets the rotation in degrees.
Name Type Required What it is xnumber|Vec3yes ynumberoptional znumberoptional
Returns: void
enemy.setRotation3D(0, 180, 0);
Watch out: Degrees.
# node.setScale3D(x, y?, z?)
method 3D VYOM
Sets the scale.
Name Type Required What it is xnumber|Vec3yes ynumberoptional znumberoptional
Returns: void
enemy.setScale3D(2);
Watch out: One number scales all axes.
# node.setVelocity3D(x, y?, z?)
method 3D VYOM
Sets the velocity of the referenced body.
Name Type Required What it is xnumber|Vec3yes ynumberoptional znumberoptional
Returns: void
enemy.setVelocity3D(0, 0, -3);
Watch out: Needs a body node.
# node.moveAndSlide3D()
method 3D VYOM
Runs moveAndSlide on the referenced CharacterBody3D.
No parameters.
Returns: boolean
enemy.moveAndSlide3D();
Watch out: Only CharacterBody3D.
# node.isOnFloor3D()
method 3D VYOM
True if the referenced body is on the floor.
No parameters.
Returns: boolean
if (enemy.isOnFloor3D()) { }
Watch out: Only CharacterBody3D.
# node.isColliding3D()
method 3D VYOM
True if the body collided in its last move.
No parameters.
Returns: boolean
if (enemy.isColliding3D()) { }
Watch out: Only CharacterBody3D.
# node.playAnimation3D(name)
method 3D VYOM
Plays an animation of the referenced node.
Name Type Required What it is namestringyes Animation name
Returns: void
enemy.playAnimation3D("walk");
Watch out: Needs an AnimationPlayer.
# node.stopAnimation3D()
method 3D VYOM
Stops the animation.
No parameters.
Returns: void
enemy.stopAnimation3D();
Watch out: No-op if idle.
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.
Global Y position (height).
Type: number
lift.y = 3;
Watch out: Y is UP in 3D.
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?)
method 3D VYOM
Puts the node at x, y, z. Same as setPosition3D, written like the 2D setPosition.
Name Type Required What it is xnumber|Vec3yes X or a vector ynumberoptional Y znumberoptional Z
Returns: Node3DRef
key.setPosition(2, 1, -4);
Watch out: Teleports: physics bodies keep their velocity.
# node.hide()
method 3D VYOM
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()
method 3D VYOM
Shows the node again.
No parameters.
Returns: Node3DRef
key.show();
Watch out: Opposite of hide().
# node.setLight(energy?, color?, range?)
method 3D VYOM
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.
Name Type Required What it is energynumberoptional Brightness. 0 turns the light off colorstringoptional Light colour like "orange" or "#ffeecc" rangenumberoptional How 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?)
method 3D VYOM
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.
Name Type Required What it is targetNode3DRef|Vec3|Arrayyes A node from getNode3D(), a point, or an array / group of them marginnumberoptional Extra 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?)
method 3D VYOM
Same as isTouching().
Name Type Required What it is targetNode3DRef|Vec3|Arrayyes Target marginnumberoptional Extra 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)
method 3D VYOM
True only if the shapes really overlap (just touching surfaces do not count).
Name Type Required What it is targetNode3DRef|Vec3|Arrayyes Target
Returns: boolean
if (zone.isOverlapping(player)) { print("inside the room"); }
Watch out: See isTouching.
# node.touched(target, margin?)
method 3D VYOM
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.
Name Type Required What it is targetNode3DRef|Vec3|Arrayyes Target marginnumberoptional Extra 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?)
method 3D VYOM
Distance in metres from this node to a point or node.
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, a vector or the X of a point ynumberoptional Y when the first argument is a number znumberoptional Z 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?)
method 3D VYOM
Distance in metres on the ground (height ignored).
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, a vector or the X of a point ynumberoptional Y (ignored) znumberoptional Z 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?)
method 3D VYOM
The turn in degrees (around Y) that makes this node face the target. 0 = looking along -Z.
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, a vector or the X of a point ynumberoptional Y (ignored) znumberoptional Z
Returns: number
self.rotation = vec3(0, self.angleTo(player), 0);
Watch out: Degrees. Use faceTowards() to do it in one step.
# node.forward()
method 3D VYOM
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?)
function 3D VYOM
In a script attached to a 3D node: true if that node touches the target. Same as self.isTouching(target).
Name Type Required What it is targetNode3DRef|Vec3|Arrayyes What to test against marginnumberoptional Extra 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)
function 3D VYOM
Like isTouching() but touching surfaces do not count.
Name Type Required What it is targetNode3DRef|Vec3|Arrayyes What to test against
Returns: boolean
if (isOverlapping(getNode3D("SafeRoom"))) { print("safe"); }
Watch out: Only in scripts attached to a node.
# touched(target, margin?)
function 3D VYOM
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).
Name Type Required What it is targetNode3DRef|Vec3|Arrayyes What to test against marginnumberoptional Extra 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?)
function 3D VYOM
Distance in metres from the node this script is attached to.
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, vector or X ynumberoptional Y znumberoptional Z
Returns: number
if (distanceTo(getNode3D("Player")) < 5) { print("near"); }
Watch out: Only in scripts attached to a node.
# flatDistanceTo(x_or_target, y?, z?)
function 3D VYOM
Distance on the ground (height ignored) from the node this script is attached to.
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, vector or X ynumberoptional Y (ignored) znumberoptional Z
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?)
function 3D VYOM
Turn in degrees that makes this node face the target.
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, vector or X ynumberoptional Y (ignored) znumberoptional Z
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?)
method 3D VYOM
Turns the node around the Y axis so it looks at the target, staying level (it does not tilt up or down).
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, vector or X ynumberoptional Y (ignored) znumberoptional Z
Returns: Node3DRef
enemy.faceTowards(player);
Watch out: Instant. For a smooth turn use turnTowards().
# node.turnTowards(target, degreesPerSecond)
method 3D VYOM
Turns smoothly (the short way round) towards the target. Call it every frame.
Name Type Required What it is targetNode3DRef|Vec3yes Node or point to turn to degreesPerSecondnumberyes Turn 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?)
method 3D VYOM
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).
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, vector or the X of a point y_or_speednumberyes Speed (metres per second) when a node was given, otherwise Y znumberoptional Z when numbers were given speednumberoptional Speed 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?)
method 3D VYOM
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.
Name Type Required What it is targetNode3DRef|Vec3yes Node or point to walk to speednumberyes Metres per second stopDistancenumberoptional Stop 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?)
method 3D VYOM
Strolls to random spots around where it started, pausing now and then. Call it every frame.
Name Type Required What it is speednumberyes Metres per second radiusnumberoptional How far from its starting spot it may go (default 8) pauseSecondsnumberoptional Pause 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?)
method 3D VYOM
Walks a loop through the points, forever. Call it every frame.
Name Type Required What it is pointsArrayyes Points to walk through: vec3(...), [x,y,z] or nodes speednumberyes Metres per second waitSecondsnumberoptional Pause 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?)
method 3D VYOM
Line of sight: true if the target is in range and view angle and nothing solid is in between.
Name Type Required What it is targetNode3DRef|Vec3yes What to look at maxDistancenumberoptional How far it can see in metres fovnumberoptional Field of view in degrees (default: all around) eyeHeightnumberoptional Height 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?)
function 3D VYOM
In a script attached to a 3D node: walk towards the target and face it. Same as self.chase().
Name Type Required What it is targetNode3DRef|Vec3yes Node or point speednumberyes Metres per second stopDistancenumberoptional Stop 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?)
function 3D VYOM
In a script attached to a 3D node: stroll around the starting spot.
Name Type Required What it is speednumberyes Metres per second radiusnumberoptional Radius (default 8) pauseSecondsnumberoptional Pause (default 2)
Returns: void
function update() { wander(1.5, 10); }
Watch out: Call it every frame.
# patrol(points, speed, waitSeconds?)
function 3D VYOM
In a script attached to a 3D node: walk a loop through points.
Name Type Required What it is pointsArrayyes Points to walk through speednumberyes Metres per second waitSecondsnumberoptional Pause 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?)
function 3D VYOM
In a script attached to a 3D node: move straight towards a point (metres per second).
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, vector or X y_or_speednumberyes Speed or Y znumberoptional Z speednumberoptional Speed
Returns: boolean
function update() { moveTowards(0, 5, 0, 1); }
Watch out: Goes through walls.
# faceTowards(x_or_target, y?, z?)
function 3D VYOM
In a script attached to a 3D node: look at the target (staying level).
Name Type Required What it is x_or_targetnumber|Node3DRef|Vec3yes A node, vector or X ynumberoptional Y (ignored) znumberoptional Z
Returns: Node3DRef
faceTowards(getNode3D("Player"));
Watch out: Instant.
# turnTowards(target, degreesPerSecond)
function 3D VYOM
In a script attached to a 3D node: turn smoothly towards the target.
Name Type Required What it is targetNode3DRef|Vec3yes Node or point degreesPerSecondnumberyes Turn speed
Returns: Node3DRef
turnTowards(getNode3D("Player"), 90);
Watch out: Call it every frame.
# canSee(target, maxDistance?, fov?, eyeHeight?)
function 3D VYOM
In a script attached to a 3D node: line of sight to the target.
Name Type Required What it is targetNode3DRef|Vec3yes What to look at maxDistancenumberoptional Range in metres fovnumberoptional Field of view in degrees eyeHeightnumberoptional Eye 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?)
method 3D VYOM
True while the crosshair (the middle of the screen) is on this node. Perfect for "press E to pick up".
Name Type Required What it is maxDistancenumberoptional How 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()
method 3D VYOM
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()
method 3D VYOM
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()
method 3D VYOM
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()
method 3D VYOM
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?)
function 3D VYOM
What the crosshair points at: {hit, position, normal, distance, collider} or null. In a script attached to a node, that node itself is ignored.
Name Type Required What it is distancenumberoptional How 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?)
function 3D VYOM
True while the crosshair is on that node.
Name Type Required What it is nodeNode3DRefyes The node to check distancenumberoptional How 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)
function 3D VYOM
Stores a value that EVERY script can read with getGlobal(). (A normal var belongs to one script only.)
Name Type Required What it is namestringyes Name of the value valueanyyes What 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?)
function 3D VYOM
Reads a value stored with setGlobal(), from any script.
Name Type Required What it is namestringyes Name of the value fallbackanyoptional Returned 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?)
function 3D VYOM
Puts an item in the inventory (shared by all scripts). Returns how many you now have.
Name Type Required What it is namestringyes Item name, e.g. "key" countnumberoptional How many (default 1)
Returns: number
giveItem("key");
giveItem("battery", 2);
Watch out: Item names are case sensitive.
# takeItem(name, count?)
function 3D VYOM
Removes items from the inventory. Returns false (and takes nothing) if you do not have enough.
Name Type Required What it is namestringyes Item name countnumberoptional How 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?)
function 3D VYOM
True if the inventory holds at least that many.
Name Type Required What it is namestringyes Item name countnumberoptional How 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)
function 3D VYOM
How many of an item you have (0 if none).
Name Type Required What it is namestringyes Item name
Returns: number
function draw() {
text("Batteries: " + itemCount("battery"), 20, 30);
}
Watch out: Returns 0, never undefined.
# getItems()
function 3D VYOM
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?)
function 3D VYOM
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.
Name Type Required What it is textstringyes What to show secondsnumberoptional How 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
Information about the 3D world.
Type: object
print(World3D.gravity);
Watch out: Use World for 2D.
# World3D.gravity
property 3D VYOM
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
property 3D VYOM
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
property 3D VYOM
Seconds per physics step.
Type: number read-only
print(World3D.physicsDelta);
Watch out: Usually 1/60.
# World3D.frameCount
property 3D VYOM
Frames since the game started.
Type: number read-only
if (World3D.frameCount % 60 === 0) { tick(); }
Watch out: Counts frames.
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
property 3D VYOM
Camera position (global).
Type: Vec3
camera3D.position = vec3(0, 5, 10);
Watch out: Assign a whole vector.
# camera3D.rotation
property 3D VYOM
Camera rotation in degrees.
Type: Vec3
camera3D.rotation = vec3(-20, 0, 0);
Watch out: Degrees.
# camera3D.follow(target, smoothing?)
method 3D VYOM
Keeps the camera following a node from its current offset every frame.
Name Type Required What it is targetNode3DRefyes Node to follow smoothingnumberoptional 0.01 to 1 (1 = snap)
Returns: void
camera3D.follow(getNode3D("Player"), 0.15);
Watch out: Pass null to stop.
# camera3D.lookAt(target)
method 3D VYOM
Points the camera at a target.
Name Type Required What it is targetVec3|Node3DRefyes Point or node
Returns: void
camera3D.lookAt(getNode3D("Player"));
Watch out: Call it every frame for a moving target.
# camera3D.shake(strength?, seconds?)
method 3D VYOM
Shakes the picture for a moment and then calms down. Use it for jump scares, explosions or a hard landing.
Name Type Required What it is strengthnumberoptional How far the picture wobbles (0.05 = small, 0.3 = big). Default 0.1 secondsnumberoptional How 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?)
method 3D VYOM
Fills the 3D world with fog. Dark thick fog is the classic horror look: you only see a few metres ahead.
Name Type Required What it is densitynumberyes 0.02 = light mist, 0.1 = medium, 0.3 or more = very thick (you see only a few metres), 0 = no fog colorstringoptional Fog 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()
method 3D VYOM
Turns the fog off again.
No parameters.
Returns: void
World3D.fogOff();
Watch out: Fog is on only after setFog().
# World3D.setAmbientLight(color, energy?)
method 3D VYOM
Sets how bright the shadows are. A very low value makes the world dark so that your flashlight and lamps matter.
Name Type Required What it is colorstringyes Colour of the light that reaches everywhere, like "#202838" energynumberoptional Brightness, 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)
method 3D VYOM
Replaces the sky by one plain colour (for example black for a night scene or an indoor level).
Name Type Required What it is colorstringyes Colour of the sky / background
Returns: void
World3D.setSkyColor("black");
Watch out: Use the same colour as the fog.
Engine 17
# loadScene(name)
function 2D + 3D VYOM
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").
Name Type Required What it is namestringyes Name 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)
function 2D + 3D VYOM
Same as loadScene(): switches to another scene at the end of the frame.
Name Type Required What it is pathstringyes Scene 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()
function 2D + 3D VYOM
Closes the game.
No parameters.
Returns: void
if (keyDown("escape")) { quitGame(); }
Watch out: In the editor this stops the play session.
# saveData(key, value)
function 2D + 3D VYOM
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).
Name Type Required What it is keystringyes A name for this saved thing, like "highscore" valueanyyes A 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?)
function 2D + 3D VYOM
Reads back something saved with saveData. If nothing was saved yet you get the fallback value.
Name Type Required What it is keystringyes The name you used in saveData fallbackanyoptional What 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)
function 2D + 3D VYOM
True if something is saved under that name.
Name Type Required What it is keystringyes The 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?)
function 2D + 3D VYOM
Deletes a saved value (or all saved values when you give no name). Use it for a "New game" button.
Name Type Required What it is keystringoptional What to forget. Leave empty to forget everything
Returns: void
deleteData("level"); // one thing
deleteData(); // everything
Watch out: This cannot be undone.
# setFullscreen(on?)
function 2D + 3D VYOM
Switches the game window between fullscreen and a normal window.
Name Type Required What it is onbooleanoptional true = 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.
Calls a function once after a delay (game time).
Name Type Required What it is fnfunctionyes Function to call msnumberyes Delay in milliseconds
Returns: number
setTimeout(function () { player.visible = true; }, 2000);
Watch out: Time only advances while the game runs; it pauses with the game.
Calls a function repeatedly.
Name Type Required What it is fnfunctionyes Function to call msnumberyes Interval in milliseconds
Returns: number
var id = setInterval(spawnEnemy, 1000);
Watch out: Clear it with clearInterval(id).
Cancels a timeout.
Name Type Required What it is idnumberyes Id from setTimeout
Returns: void
clearTimeout(id);
Watch out: Unknown ids are ignored.
Cancels an interval.
Name Type Required What it is idnumberyes Id from setInterval
Returns: void
clearInterval(id);
Watch out: Unknown ids are ignored.
Writes to the Output panel.
Name Type Required What it is values...anyyes Things to show
Returns: void
print("score", score);
Watch out: Objects are shown as JSON.
Same as print().
Name Type Required What it is values...anyyes Things to show
Returns: void
console.log("hi");
Watch out: Same output as print(); pick one style and stay with it.
Like print() with an info mark.
Name Type Required What it is values...anyyes Things to show
Returns: void
console.info("loaded");
Watch out: Shown in the Output panel only; it is not an error or warning.
Writes a warning (yellow) that also appears in the Warnings tab.
Name Type Required What it is values...anyyes Things to show
Returns: void
console.warn("low health");
Watch out: Warnings do not stop the game.
Writes an error (red) that appears in the Errors tab.
Name Type Required What it is values...anyyes Things to show
Returns: void
console.error("bad state");
Watch out: It does not stop the game; thrown errors do.
Sound 25
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).
Name Type Required What it is namestring|string[]yes A 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|objectoptional Volume 0 to 1, true to loop (Game Lab style), or an options object like { volume: 0.5, pitchRandom: 2 } optionsobject|booleanoptional Options 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?)
function 2D + 3D VYOM
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().
Name Type Required What it is namestring|string[]yes Sound name or file xnumber|Sprite|Nodeyes X position, or a sprite / node to play the sound from ynumberoptional Y position znumberoptional Z position (3D games only) optionsobjectoptional Same 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?)
function 2D + 3D VYOM
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.
Name Type Required What it is namestringyes Music 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?)
function 2D + 3D VYOM
Fades the music out and stops it.
Name Type Required What it is fadenumberoptional Seconds 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.
Stops one sound by name (all copies of it), one SoundRef, or every sound.
Name Type Required What it is whatstring|SoundRef|numberoptional Sound name, a SoundRef, or nothing for every sound (music too) fadenumberoptional Seconds 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?)
function 2D + 3D VYOM
Smoothly changes the volume of a playing sound.
Name Type Required What it is whatstring|SoundRefyes Sound name or a SoundRef volumenumberyes Volume to fade to (0 to 1) secondsnumberoptional How 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()
function 2D + 3D VYOM
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()
function 2D + 3D VYOM
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?)
function 2D + 3D VYOM
Sets the loudness of the whole game: every sound and the music.
Name Type Required What it is volumenumberyes 0 (silent) to 1 (normal), up to 2 fadenumberoptional Seconds 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?)
function 2D + 3D VYOM
Sets the loudness of all music.
Name Type Required What it is volumenumberyes 0 to 1 fadenumberoptional Seconds 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?)
function 2D + 3D VYOM
Sets the loudness of all sound effects.
Name Type Required What it is volumenumberyes 0 to 1 fadenumberoptional Seconds to fade (default 0)
Returns: void
setSfxVolume(0.7);
Watch out: Only affects the "sfx" group (the default for playSound).
# setBusVolume(bus, volume, fade?)
function 2D + 3D VYOM
Sets the loudness of one sound group (a "bus"). Every sound belongs to a group: sfx (default), music, ui (button clicks) or voice (speech).
Name Type Required What it is busstringyes "master", "music", "sfx", "ui" or "voice" volumenumberyes 0 to 1 fadenumberoptional Seconds 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)
function 2D + 3D VYOM
Reads the volume of a sound group, for example to draw a volume slider.
Name Type Required What 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()
function 2D + 3D VYOM
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?)
function 2D + 3D VYOM
Mutes or unmutes the whole game without changing the volume setting.
Name Type Required What it is onbooleanoptional true 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?)
function 2D + 3D VYOM
Mutes one sound group.
Name Type Required What it is busstringyes "master", "music", "sfx", "ui" or "voice" onbooleanoptional true to mute (default true)
Returns: void
muteBus("music", true);
Watch out: Unmute with muteBus("music", false).
# duckMusic(level?, seconds?)
function 2D + 3D VYOM
Lowers the music for a moment (called "ducking") so speech or an important sound can be heard. Undo it with unduckMusic().
Name Type Required What it is levelnumberoptional How loud the music stays, 0 to 1 (default 0.3) secondsnumberoptional Fade 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?)
function 2D + 3D VYOM
Brings the music back to its normal volume after duckMusic().
Name Type Required What it is secondsnumberoptional Fade time (default 0.5)
Returns: void
unduckMusic(1);
Watch out: Does nothing if the music was not ducked.
# playSoundWhen(condition, name, options?)
function 2D + 3D VYOM
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.
Name Type Required What it is conditionbooleanyes Something that is true or false, like player.isTouching(coin) namestring|string[]yes Sound name or file optionsobjectoptional Same 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?)
function 2D + 3D VYOM
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.
Name Type Required What it is conditionbooleanyes Something that is true or false namestringyes Sound name or file (it loops) optionsobjectoptional Same 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)
function 2D + 3D VYOM
Tells whether a sound (preset or file) can be found.
Name Type Required What it is namestringyes Sound 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)
function 2D + 3D VYOM
How long a sound file is.
Name Type Required What it is namestringyes Sound 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)
function 2D + 3D VYOM
Tells whether a sound is playing right now.
Name Type Required What it is namestringyes Sound name or file
Returns: boolean
if (!isSoundPlaying("siren")) { playSound("siren"); }
Watch out: A paused sound counts as not playing.
# getPlayingSounds()
function 2D + 3D VYOM
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?)
function 2D VYOM
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.
Name Type Required What it is xnumber|Sprite|Nodeoptional X position, or a sprite to listen from. Pass nothing to follow the camera again ynumberoptional Y position
Returns: void
setSoundListener(player);
Watch out: In 3D the active camera is the listener automatically.
Sound references 15
# sound.stop(fade?)
method 2D + 3D VYOM
Stops this sound (optionally with a fade-out).
Name Type Required What it is fadenumberoptional Seconds 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()
method 2D + 3D VYOM
Pauses this sound where it is.
No parameters.
Returns: SoundRef
s.pause();
Watch out: Continue with resume().
# sound.resume()
method 2D + 3D VYOM
Continues a paused sound.
No parameters.
Returns: SoundRef
s.resume();
Watch out: Nothing happens if the sound was not paused.
# sound.fadeTo(volume, seconds?)
method 2D + 3D VYOM
Smoothly changes the volume of this sound.
Name Type Required What it is volumenumberyes Volume to reach (0 to 1) secondsnumberoptional How 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?)
method 2D + 3D VYOM
Fades the sound to silence, then stops it.
Name Type Required What it is secondsnumberoptional Fade time (default 1)
Returns: SoundRef
s.fadeOut(2);
Watch out: Same as stop(seconds).
# sound.setPosition(x, y?, z?)
method 2D + 3D VYOM
Moves a sound made with playSoundAt(). Call it every frame for a moving thing.
Name Type Required What it is xnumber|Sprite|Nodeyes X position or a sprite / node ynumberoptional Y position znumberoptional Z 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
property 2D + 3D VYOM
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
property 2D + 3D VYOM
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
property 2D + 3D VYOM
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
property 2D + 3D VYOM
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
property 2D + 3D VYOM
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
property 2D + 3D VYOM
true while the sound is paused.
Type: boolean read-only
if (s.isPaused) { s.resume(); }
Watch out: Read only.
# sound.time
property 2D + 3D VYOM
Where the sound is, in seconds.
Type: number read-only
text(s.time.toFixed(1), 10, 20);
Watch out: Read only.
# sound.length
property 2D + 3D VYOM
Length of the sound file in seconds.
Type: number read-only
var left = s.length - s.time;
Watch out: Read only.
# sound.name
property 2D + 3D VYOM
The name you gave playSound().
Type: string read-only
print(s.name);
Watch out: Read only.
No command matches that. Try a shorter word, like move or sound.
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:
Topic Difference Game loop Game 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 size Game Lab is always 400x400. In Nova it is set in Project Settings; read it with World.width / World.height. sprite.mirrorX Game Lab: sprite.mirrorX(-1) (a function). Nova: sprite.mirrorX = true (a property; -1 also works when assigned). Images and animations Use 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"). Sounds playSound("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 shapes Colliders do not rotate (same as Game Lab). sprite.debug = true shows them. Whole numbers random() is p5-style (decimals). Game Lab's randomNumber(min, max) returns whole numbers and is available. Errors Errors 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 command Instead 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 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). 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(). Replace asset URLs ("sound://...", "asset://...") with project files: drag your images/sounds into the FileSystem dock, then use assets/yourfile.png. Replace the commands listed under not implemented above. Check the Known differences table: sprite.mirrorX(-1) becomes sprite.mirrorX = true, and the world size comes from Project Settings. Run the project. Errors show the exact file and line.
Common errors Message Meaning 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 appear Call 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 ground Use 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 keyDown Click the game window once to give it keyboard focus. Key names: "LEFT_ARROW", "a", "space", "enter", "shift". Exported variable not shown in the Inspector The line must be a top-level var name = value; // @export (not let, not inside a function).
VYOM Engine 1.0.0 · Scripting documentation, generated from the engine itself: every command listed here exists in the engine and every example is checked by an automatic test.
Built with Godot Engine, Node.js, Electron and Monaco Editor (all MIT license). Games you make belong to you.