Skip to content

The Engine and three.js ​

The engine is built on three.js, and a script can use all of three.js. What decides which to reach for is who owns the thing you're changing.

The engine owns everything an entity has: where it is, what it looks like, how it moves, what it plays. Change those through components, or the next frame puts them back. three.js is the toolbox for what the engine doesn't do: maths, custom geometry, shaders, particles.

Which one to use ​

To do thisUseNot
Move or turn somethingthis.transform, in radiansthreeRef.object.position: overwritten every frame
Move a physics characterrigidBody.setLinvel()this.transform: physics owns a dynamic body
Follow something with the cameraA Camera Rig, or onLateUpdatecamera.position, OrbitControls
Load a modelA Model entity, or spawnPrefabGLTFLoader: it misses the cache, the optimised formats and the asset paths of a published game
Play animationAnimationComponent.switchState()THREE.AnimationMixer
Play soundAn Audio entity, or playSlotTHREE.Audio
Change a colourMaterialComponent.updateValue(0, { color })mesh.material.color: reset by the sync, and the material may be shared
Add a lightA Light entitynew THREE.PointLight(): invisible to the editor and the save
Add post-processingThe Environment's post-processingA composer of your own, unless nothing built in does it
Hold something in a handattachToBonebone.add(mesh)
Aim, measure, interpolateTHREE.Vector3, Quaternion, MathUtils, freelyWriting your own
Procedural meshes, shaders, particlesA Script Object
Thousands of copiesInstanced meshesOne entity each
Things three.js ships as addonsimport { X } from "three/addons/..."

Before reaching for three.js, check the component list. The usual way to end up with a slow, broken scene is rebuilding something the engine already does.

Adding a three.js object ​

Build it in a Script Object when it should show in the editor. It returns the object, and the engine attaches and cleans up:

ts
import { ScriptObject } from "@relu-interactives/spatial-ecs";
import * as THREE from "three";

export default class Ring extends ScriptObject {
  private mesh: THREE.Mesh | null = null;

  build() {
    this.mesh = new THREE.Mesh(
      new THREE.TorusGeometry(1, 0.1, 16, 64),
      new THREE.MeshStandardMaterial({ color: "#ff7a45" }),
    );
    return this.mesh;
  }

  update(deltaTime: number) {
    if (this.mesh) this.mesh.rotation.y += deltaTime;
  }
}

For something that only exists while the game runs, add it to the entity's object from a Behaviour, and take it out again:

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";
import * as THREE from "three";

export default class Marker extends Behaviour {
  private mesh: THREE.Mesh | null = null;

  protected init() {
    this.mesh = new THREE.Mesh(
      new THREE.SphereGeometry(0.2),
      new THREE.MeshBasicMaterial({ color: "#6dd58c" }),
    );
    this.mesh.position.y = 2;
    this.threeRef.object.add(this.mesh);
  }

  dispose() {
    if (!this.mesh) return;
    this.threeRef.object.remove(this.mesh);
    this.mesh.geometry.dispose();
    (this.mesh.material as THREE.Material).dispose();
  }
}

The object's own children are yours. Only the entity's root object is overwritten from its Transform, so animate children freely.

Reading where something is ​

ValueWhat it isUse it for
this.transform.positionLocal position. For a physics body, shown smoothly between stepsAlmost everything, cameras included
rigidBody.translation()Exactly where physics has it, moving in fixed stepsPhysics logic, such as checking how far a body moved in a step
threeRef.object.getWorldPosition(v)World position, including parentsA child entity, or a bone. Up to date in onLateUpdate

Time ​

Use this.deltaTime. Ease with damp, dampAngle and dampVector3, where the number is the seconds it takes to close most of the gap, so a game feels the same at 60 Hz and 144 Hz:

ts
import { Behaviour, damp } from "@relu-interactives/spatial-ecs";

export default class Glow extends Behaviour {
  private level = 0;

  protected onUpdate() {
    this.level = damp(this.level, 1, 0.2, this.deltaTime);
  }
}

Math.min(1, speed * this.deltaTime) looks like the same thing and isn't: it moves a different amount on a long frame than on two short ones.

The order of a frame ​

World.update(dt)
  ├── objects, geometry, environment
  ├── physics           # fixed steps, then bodies shown between them
  ├── input
  ├── onUpdate          # your scripts
  ├── animation, held objects, IK
  ├── sync to three.js  # Transforms reach the scene here
  ├── onLateUpdate      # your cameras: everything has moved
  ├── Camera Rig, cutscenes
  └── render
  • Set velocities in onUpdate. Physics applies them next frame.
  • A change to this.transform in onUpdate shows the same frame.
  • Animation runs after onUpdate, so it overwrites a script's change to a bone. Change bones in onLateUpdate, or with IK.