Skip to content

@relu-interactives/spatial-ecs


@relu-interactives/spatial-ecs / index / World

Class: World ​

Defined in: World.ts:129

Constructors ​

Constructor ​

ts
new World(options): World;

Defined in: World.ts:208

Parameters ​

ParameterTypeDescription
options{ scene: Scene; camera: PerspectiveCamera; renderer: EcsRenderer; backend?: RenderBackend; featureFlags?: WorldFeatureFlags; gameId?: string; }-
options.sceneScene-
options.cameraPerspectiveCamera-
options.rendererEcsRendererA THREE.WebGLRenderer, or a WebGPURenderer from three/webgpu. A WebGPURenderer must be initialised (await renderer.init()) before the first update().
options.backend?RenderBackendRenderer-specific behaviour (post-processing, green-screen video, area lights). Defaults to the WebGL backend; pass webgpuBackend from @relu-interactives/spatial-ecs/webgpu with a WebGPURenderer.
options.featureFlags?WorldFeatureFlags-
options.gameId?stringNames this game for saved settings (relu-game-settings:<gameId>), so two games on one site keep their own volume and graphics choices.

Returns ​

World

Accessors ​

settings ​

Get Signature ​

ts
get settings(): GameSettings;

Defined in: World.ts:429

The player's settings: graphics, audio, controls and gameplay, saved between visits. The engine applies its own parts; a settings screen reads and writes here.

ts
world.settings.update({ audio: { music: 0.4 } });
Returns ​

GameSettings


input ​

Get Signature ​

ts
get input(): InputSystem | null;

Defined in: World.ts:436

The input system with actions, gamepads and touch, or null when the host added none.

Returns ​

InputSystem | null


quality ​

Get Signature ​

ts
get quality(): QualitySystem | null;

Defined in: World.ts:441

Graphics quality: presets, the device and its recommendation, fps. Null without a QualitySystem.

Returns ​

QualitySystem | null


streaming ​

Get Signature ​

ts
get streaming(): StreamingSystem | null;

Defined in: World.ts:1463

World streaming: loads regions of a big world as the player comes near and frees them from memory once they're far (StreamingComponent). Change what distance is measured from with setFocus (the camera by default), the load concurrency and memory budget in settings, and read getStats(world). Null before setup.

ts
this.world.streaming?.setFocus(this.entityId);
Returns ​

StreamingSystem | null


lod ​

Get Signature ​

ts
get lod(): LODSystem | null;

Defined in: World.ts:1476

Levels of detail (LODComponent): bias multiplies every screen size (null follows the quality preset), switches counts level changes.

Returns ​

LODSystem | null


occlusion ​

Get Signature ​

ts
get occlusion(): OcclusionCullingSystem | null;

Defined in: World.ts:1485

Occlusion culling (OccluderComponent): enabled, xr (also in a headset), maxOccluders, getStats(), and addOccluderSource for systems with their own occluders.

Returns ​

OcclusionCullingSystem | null


terrain ​

Get Signature ​

ts
get terrain(): TerrainSystem | null;

Defined in: World.ts:1498

Terrains (TerrainComponent): heightAt(world, x, z) and normalAt(world, x, z) read the ground in world space; edit(id) gives a terrain's heightfield to sculpt and paint; save(id) its .terrain file.

ts
const ground = this.world.terrain?.heightAt(this.world, x, z);
Returns ​

TerrainSystem | null


foliage ​

Get Signature ​

ts
get foliage(): FoliageSystem | null;

Defined in: World.ts:1503

Grass and scattered models on terrains: getStats().

Returns ​

FoliageSystem | null

Methods ​

createEntity() ​

ts
createEntity(): number;

Defined in: World.ts:239

Returns ​

number


destroyEntity() ​

ts
destroyEntity(entityId): void;

Defined in: World.ts:247

Parameters ​

ParameterType
entityIdnumber

Returns ​

void


hasEntity() ​

ts
hasEntity(entityId): boolean;

Defined in: World.ts:274

Parameters ​

ParameterType
entityIdnumber

Returns ​

boolean


getEntities() ​

ts
getEntities(): number[];

Defined in: World.ts:278

Returns ​

number[]


getEntityCount() ​

ts
getEntityCount(): number;

Defined in: World.ts:282

Returns ​

number


addComponent() ​

ts
addComponent<T>(entityId, component): void;

Defined in: World.ts:286

Type Parameters ​

Type Parameter
T extends Component

Parameters ​

ParameterType
entityIdnumber
componentT

Returns ​

void


addComponents() ​

ts
addComponents<T>(entityId, components): void;

Defined in: World.ts:301

Type Parameters ​

Type Parameter
T extends Component

Parameters ​

ParameterType
entityIdnumber
componentsT[]

Returns ​

void


removeComponent() ​

ts
removeComponent<T>(entityId, componentType): void;

Defined in: World.ts:322

Type Parameters ​

Type Parameter
T extends Component

Parameters ​

ParameterType
entityIdnumber
componentTypeComponentClass<T>

Returns ​

void


getComponent() ​

ts
getComponent<T>(entityId, componentType): T | undefined;

Defined in: World.ts:330

Type Parameters ​

Type Parameter
T extends Component

Parameters ​

ParameterType
entityIdnumber
componentTypeComponentClass<T>

Returns ​

T | undefined


hasComponent() ​

ts
hasComponent<T>(entityId, componentType): boolean;

Defined in: World.ts:337

Type Parameters ​

Type Parameter
T extends Component

Parameters ​

ParameterType
entityIdnumber
componentTypeComponentClass<T>

Returns ​

boolean


query() ​

ts
query(...componentTypes): number[];

Defined in: World.ts:344

Parameters ​

ParameterType
...componentTypesComponentClass<Component>[]

Returns ​

number[]


getStoreVersion() ​

ts
getStoreVersion(): number;

Defined in: World.ts:405

A number that changes whenever an entity or component is added or removed. Systems compare it to skip work when nothing came or went.

Returns ​

number


isEntityVisible() ​

ts
isEntityVisible(entityId): boolean;

Defined in: World.ts:415

Returns true if the entity is currently visible (its Object3DRef.visibility is true), or if the entity has no Object3DRef component (entities without a scene object are always considered active). Systems use this to skip per-entity updates for hidden objects.

Parameters ​

ParameterType
entityIdnumber

Returns ​

boolean


getQualityLimits() ​

ts
getQualityLimits(): QualityLimits | null;

Defined in: World.ts:451

What the quality system applies now. Lights and post effects read it.

Returns ​

QualityLimits | null


getInputSystem() ​

ts
getInputSystem(): EcsSystem | null;

Defined in: World.ts:460

Returns ​

EcsSystem | null


getKeyDown() ​

ts
getKeyDown(key): boolean;

Defined in: World.ts:472

Parameters ​

ParameterType
keyKeyboardKey

Returns ​

boolean


getKeyUp() ​

ts
getKeyUp(key): boolean;

Defined in: World.ts:481

Parameters ​

ParameterType
keyKeyboardKey

Returns ​

boolean


getKey() ​

ts
getKey(key): boolean;

Defined in: World.ts:490

Parameters ​

ParameterType
keyKeyboardKey

Returns ​

boolean


getMouse() ​

ts
getMouse(button): boolean;

Defined in: World.ts:499

Parameters ​

ParameterType
buttonstring | number

Returns ​

boolean


getMouseDown() ​

ts
getMouseDown(button): boolean;

Defined in: World.ts:508

Parameters ​

ParameterType
buttonstring | number

Returns ​

boolean


getMouseUp() ​

ts
getMouseUp(button): boolean;

Defined in: World.ts:517

Parameters ​

ParameterType
buttonstring | number

Returns ​

boolean


getScrollClick() ​

ts
getScrollClick(): boolean;

Defined in: World.ts:526

Returns ​

boolean


getScrollClickDown() ​

ts
getScrollClickDown(): boolean;

Defined in: World.ts:535

Returns ​

boolean


getScrollClickUp() ​

ts
getScrollClickUp(): boolean;

Defined in: World.ts:544

Returns ​

boolean


getScrollDelta() ​

ts
getScrollDelta(): {
  x: number;
  y: number;
};

Defined in: World.ts:553

Returns ​

ts
{
  x: number;
  y: number;
}
NameTypeDefined in
xnumberWorld.ts:553
ynumberWorld.ts:553

consumeScrollDelta() ​

ts
consumeScrollDelta(): {
  x: number;
  y: number;
};

Defined in: World.ts:562

Returns ​

ts
{
  x: number;
  y: number;
}
NameTypeDefined in
xnumberWorld.ts:562
ynumberWorld.ts:562

getMousePosition() ​

ts
getMousePosition(): {
  x: number;
  y: number;
};

Defined in: World.ts:571

Returns ​

ts
{
  x: number;
  y: number;
}
NameTypeDefined in
xnumberWorld.ts:571
ynumberWorld.ts:571

getMouseDelta() ​

ts
getMouseDelta(): {
  x: number;
  y: number;
};

Defined in: World.ts:580

Returns ​

ts
{
  x: number;
  y: number;
}
NameTypeDefined in
xnumberWorld.ts:580
ynumberWorld.ts:580

consumeMouseDelta() ​

ts
consumeMouseDelta(): {
  x: number;
  y: number;
};

Defined in: World.ts:589

Returns ​

ts
{
  x: number;
  y: number;
}
NameTypeDefined in
xnumberWorld.ts:589
ynumberWorld.ts:589

getRapierModule() ​

ts
getRapierModule(): Promise<__module>;

Defined in: World.ts:598

Returns ​

Promise<__module>


getPhysicsWorld() ​

ts
getPhysicsWorld(): World | null;

Defined in: World.ts:616

Returns ​

World | null


setPhysicsWorld() ​

ts
setPhysicsWorld(physicsWorld): void;

Defined in: World.ts:620

Parameters ​

ParameterType
physicsWorldWorld | null

Returns ​

void


createPhysicsWorld() ​

ts
createPhysicsWorld(options?): Promise<World | null>;

Defined in: World.ts:624

Parameters ​

ParameterType
options?{ gravity?: { x?: number; y?: number; z?: number; }; }
options.gravity?{ x?: number; y?: number; z?: number; }
options.gravity.x?number
options.gravity.y?number
options.gravity.z?number

Returns ​

Promise<World | null>


lockMousePointer() ​

ts
lockMousePointer(): boolean;

Defined in: World.ts:643

Returns ​

boolean


unlockMousePointer() ​

ts
unlockMousePointer(): boolean;

Defined in: World.ts:674

Returns ​

boolean


isMousePointerLocked() ​

ts
isMousePointerLocked(): boolean;

Defined in: World.ts:695

Returns ​

boolean


onPointerLockChange() ​

ts
onPointerLockChange(listener): () => void;

Defined in: World.ts:727

Listen for the pointer lock being gained or lost. Returns an unsubscribe function.

Escape while the pointer is locked is taken by the browser, which drops the lock and may never show the page a keydown. This is how a game hears it.

Parameters ​

ParameterType
listenerPointerLockListener

Returns ​

() => void

Example ​

ts
const stop = world.onPointerLockChange((locked) => {
  if (!locked) world.pause();
});
// later
stop();

getSystem() ​

ts
getSystem<T>(system): T;

Defined in: World.ts:759

Type Parameters ​

Type Parameter
T extends EcsSystem

Parameters ​

ParameterType
systemT

Returns ​

T


hasSystem() ​

ts
hasSystem<T>(system): boolean;

Defined in: World.ts:776

Type Parameters ​

Type Parameter
T extends EcsSystem

Parameters ​

ParameterType
systemT

Returns ​

boolean


addSystem() ​

ts
addSystem(system): void;

Defined in: World.ts:785

Parameters ​

ParameterType
systemEcsSystem

Returns ​

void


addSystems() ​

ts
addSystems(systems): void;

Defined in: World.ts:789

Parameters ​

ParameterType
systemsEcsSystem[]

Returns ​

void


setup() ​

ts
setup(__namedParameters): {
  objectManagementSystem: ObjectManagementSystem;
  transformSyncSystem: TransformSyncSystem;
  renderSystem: RenderSystem;
};

Defined in: World.ts:795

Parameters ​

ParameterType
__namedParameters{ systems: EcsSystem[]; isEditor?: boolean; }
__namedParameters.systemsEcsSystem[]
__namedParameters.isEditor?boolean

Returns ​

ts
{
  objectManagementSystem: ObjectManagementSystem;
  transformSyncSystem: TransformSyncSystem;
  renderSystem: RenderSystem;
}
NameTypeDefined in
objectManagementSystemObjectManagementSystemWorld.ts:796
transformSyncSystemTransformSyncSystemWorld.ts:797
renderSystemRenderSystemWorld.ts:798

isEditorMode() ​

ts
isEditorMode(): boolean;

Defined in: World.ts:930

Returns ​

boolean


isXrPresenting() ​

ts
isXrPresenting(): boolean;

Defined in: World.ts:947

true while an immersive WebXR session is actively presenting.

While presenting, three's WebXRManager OWNS the render camera: each frame updateUserCamera() writes the headset pose into the camera's position/quaternion/scale and copies the XR projection (including a derived fov) onto it. Systems that also drive the camera must stand down for the duration, or they ping-pong with the headset every frame and defeat their own dirty-checks.

Locomotion therefore moves the camera's PARENT (the XR rig) — three composes the head pose as parent.matrixWorld × headPose.

Returns ​

boolean


isXrPassthrough() ​

ts
isXrPassthrough(): boolean;

Defined in: World.ts:964

true while the session is compositing over the real world (passthrough).

Read from the session's environmentBlendMode rather than from what the app ASKED for: a request for immersive-ar can be granted as a plain opaque session, and the blend mode is the only thing that says what the user is actually looking at. additive (optical see-through) and alpha-blend (video passthrough) both mean the real world is visible behind the render.

The load-bearing consequence is that nothing may paint an opaque background: a skybox drawn over the whole framebuffer hides the room completely, which looks exactly like passthrough having failed.

Returns ​

boolean


setXrView() ​

ts
setXrView(view, options?): boolean;

Defined in: World.ts:984

What the player is shown in a passthrough session: their room, or a fully virtual world drawn over it, which is VR. Switches live, with no new session and no tap; the sky fades in or out over fade seconds (default 0.6). Everything that depends on the view switches at once: locomotion works only in virtual, and the player's rig snaps back to where it was when they return to the room, so content stays where it belongs in their room.

Answers whether the view can be shown here: virtual always, room only in a passthrough session (Quest, Android XR; never Apple Vision Pro, which gives web pages no passthrough). Each session starts in its rig's startView, whatever was set before it.

Parameters ​

ParameterType
viewXrView
options{ fade?: number; }
options.fade?number

Returns ​

boolean


getXrView() ​

ts
getXrView(): XrView;

Defined in: World.ts:995

What the player sees now: room only while the real room is showing.

Returns ​

XrView


canShowXrRoom() ​

ts
canShowXrRoom(): boolean;

Defined in: World.ts:1000

Whether this session could show the room (a passthrough session).

Returns ​

boolean


isXrRoomVisible() ​

ts
isXrRoomVisible(): boolean;

Defined in: World.ts:1010

true while the real room is meant to be seen: a passthrough session in the room view. Systems that only make sense over the real room (no artificial locomotion, subtle avatars, depth occlusion) read this rather than the session's blend mode.

Returns ​

boolean


getXrViewFadeSeconds() ​

ts
getXrViewFadeSeconds(): number;

Defined in: World.ts:1015

Seconds the last setXrView asked the sky to fade over.

Returns ​

number


pause() ​

ts
pause(options?): void;

Defined in: World.ts:1034

Pauses the game: physics, animation, IK, locomotion and every script's onUpdate stop, and playing sounds and videos hold their place. A custom system stops too unless it sets runsWhilePaused.

The world keeps rendering and reading input, so a headset stays tracked and a pause menu works: scripts get onPause, then onPausedUpdate each frame. Later systems in the frame pause() is called from already see it.

Calling it while paused does nothing. In a multiplayer room it pauses this player only: the room carries on.

Parameters ​

ParameterType
optionsPauseOptions

Returns ​

void


resume() ​

ts
resume(): void;

Defined in: World.ts:1057

Resumes the game after pause: sounds and videos that were held pick up where they were, and scripts get onResume. Physics carries on from where it stopped, with no catch-up. Calling it while running does nothing.

Returns ​

void


togglePause() ​

ts
togglePause(options?): boolean;

Defined in: World.ts:1072

pause if the game is running, resume if it is paused. Returns whether it is paused now.

Parameters ​

ParameterType
options?PauseOptions

Returns ​

boolean


onPauseChange() ​

ts
onPauseChange(listener): () => void;

Defined in: World.ts:1095

Listen for the game pausing and resuming. Called with true on pause and false on resume, after systems and scripts have heard. Returns an unsubscribe function.

Parameters ​

ParameterType
listenerPauseListener

Returns ​

() => void

Example ​

ts
const stop = world.onPauseChange((paused) => {
  overlay.hidden = !paused;
});
// later
stop();

isPaused() ​

ts
isPaused(): boolean;

Defined in: World.ts:1140

Returns true if the world is currently paused.

Returns ​

boolean

Example ​

ts
if (this.world.isPaused()) {
  this.world.resume();
}

getScene() ​

ts
getScene(): Scene;

Defined in: World.ts:1144

Returns ​

Scene


getCamera() ​

ts
getCamera(): PerspectiveCamera;

Defined in: World.ts:1148

Returns ​

PerspectiveCamera


getRenderer() ​

ts
getRenderer(): EcsRenderer;

Defined in: World.ts:1158

The renderer this world draws with: a THREE.WebGLRenderer, or a WebGPURenderer from three/webgpu. Check getRendererKind before using an API only one of them has (for example capabilities exists on WebGL only).

Returns ​

EcsRenderer


warmUpShaders() ​

ts
warmUpShaders(): Promise<number>;

Defined in: World.ts:1175

Compile the shaders of everything in the scene now, hidden objects included, instead of the first time each is drawn.

A material's first draw compiles its shader, which on a Quest was a 100-600 ms freeze per batch, and once 2.6 s when a game mode showed 50 new materials at once (Counters Ball). Call it once loading has finished, behind the loading screen, and again after spawning a batch of new kinds of things. Uses the renderer's compileAsync, so where the browser can compile in parallel (KHR_parallel_shader_compile) the page keeps running. Resolves to the number of new shader programs, or 0 where the renderer can't count them. Never throws.

Returns ​

Promise<number>


getRendererKind() ​

ts
getRendererKind(): RendererKind;

Defined in: World.ts:1192

"webgpu" when the world renders with a WebGPURenderer, else "webgl".

Returns ​

RendererKind


getRenderBackend() ​

ts
getRenderBackend(): RenderBackend;

Defined in: World.ts:1200

The renderer-specific backend in use (post-processing, green-screen video, area lights). See RenderBackend.

Returns ​

RenderBackend


update() ​

ts
update(deltaTime): void;

Defined in: World.ts:1204

Parameters ​

ParameterType
deltaTimenumber

Returns ​

void


dispose() ​

ts
dispose(): void;

Defined in: World.ts:1214

Returns ​

void


setSelectedEntity() ​

ts
setSelectedEntity(entityId): void;

Defined in: World.ts:1241

Parameters ​

ParameterType
entityIdnumber | null

Returns ​

void


getSelectedEntity() ​

ts
getSelectedEntity(): number | null;

Defined in: World.ts:1263

Returns ​

number | null


getEntitiesByComponent() ​

ts
getEntitiesByComponent(component): WorldEntityView[];

Defined in: World.ts:1323

Parameters ​

ParameterType
componentComponent

Returns ​

WorldEntityView[]


getEntitiesByName() ​

ts
getEntitiesByName(name): WorldEntityView[];

Defined in: World.ts:1337

Parameters ​

ParameterType
namestring

Returns ​

WorldEntityView[]


getEntityByName() ​

ts
getEntityByName(name): WorldEntityView | null;

Defined in: World.ts:1355

Parameters ​

ParameterType
namestring

Returns ​

WorldEntityView | null


getEntityById() ​

ts
getEntityById(entityId): WorldEntityView | null;

Defined in: World.ts:1381

Parameters ​

ParameterType
entityIdnumber

Returns ​

WorldEntityView | null


getEntitiesChildren() ​

ts
getEntitiesChildren(entityId): WorldEntityView[];

Defined in: World.ts:1389

Parameters ​

ParameterType
entityIdnumber

Returns ​

WorldEntityView[]


getEntitiesParent() ​

ts
getEntitiesParent(entityId): WorldEntityView | null;

Defined in: World.ts:1403

Parameters ​

ParameterType
entityIdnumber

Returns ​

WorldEntityView | null


spawnPrefab() ​

ts
spawnPrefab(source, options?): Promise<number>;

Defined in: World.ts:1418

Instantiate a prefab asset into this world at runtime — see spawnPrefab. Convenience wrapper so scripts and embedding apps can spawn without reaching for the object management system.

Parameters ​

ParameterType
sourceSpawnPrefabSource
options?SpawnPrefabOptions

Returns ​

Promise<number>


despawnPrefab() ​

ts
despawnPrefab(rootEntityId): number;

Defined in: World.ts:1426

Remove a spawned prefab instance (root + descendants).

Parameters ​

ParameterType
rootEntityIdnumber

Returns ​

number


getNetwork() ​

ts
getNetwork(): NetworkService | null;

Defined in: World.ts:1431

The shared-world connection, or null in a single-player run.

Returns ​

NetworkService | null


setNetwork() ​

ts
setNetwork(network): void;

Defined in: World.ts:1436

Set by NetworkSystem when it connects and clears.

Parameters ​

ParameterType
networkNetworkService | null

Returns ​

void


getAudioSystem() ​

ts
getAudioSystem(): AudioSystem | null;

Defined in: World.ts:1441

The audio system (mixer buses, sound banks), or null before setup.

Returns ​

AudioSystem | null


getCameraDirector() ​

ts
getCameraDirector(): CameraDirector;

Defined in: World.ts:1447

Cutscenes, camera shake and camera-relative input. See CameraDirector.

Returns ​

CameraDirector


getModelLoadGate() ​

ts
getModelLoadGate(): ModelLoadGate | null;

Defined in: World.ts:1507

Returns ​

ModelLoadGate | null


getIKSystem() ​

ts
getIKSystem(): IKSystem | null;

Defined in: World.ts:1512

Returns ​

IKSystem | null


getFaceTracker() ​

ts
getFaceTracker(): Face | null;

Defined in: World.ts:1521

The face tracker of a face-tracking project: expressions, and where things are on the person in front of the camera. null in the editor and in other kinds of project.

Returns ​

Face | null


setFaceTracker() ​

ts
setFaceTracker(tracker): void;

Defined in: World.ts:1529

Set by a face-tracking runtime. Attached objects read it to find the person's head, and scripts read gestures through it.

Parameters ​

ParameterType
trackerFaceTracker | null

Returns ​

void


getHandTracker() ​

ts
getHandTracker(): Hands | null;

Defined in: World.ts:1538

Hands: which are in view, their poses and gestures. null unless the project has hand tracking on, and in the editor.

Returns ​

Hands | null


setHandTracker() ​

ts
setHandTracker(tracker): void;

Defined in: World.ts:1547

Set by a project with hand tracking on, with what createHandTracker makes in @relu-interactives/spatial-ecs/hands. That's its own entry, so a project without hands doesn't carry any of it.

Parameters ​

ParameterType
trackerHandTrackerRuntime | null

Returns ​

void


getUIPanelSystem() ​

ts
getUIPanelSystem(): UIPanelSystem | null;

Defined in: World.ts:1556

The spatial-UI system, or null when this world runs without one. Use it to ask what draws a widget tree: getUIPanelSystem()?.rendererOf(world, id).

Returns ​

UIPanelSystem | null


getObjectManagementSystem() ​

ts
getObjectManagementSystem(): ObjectManagementSystem;

Defined in: World.ts:1560

Returns ​

ObjectManagementSystem


getEnvironmentComponent() ​

ts
getEnvironmentComponent(): Environment | undefined;

Defined in: World.ts:1588

Returns the singleton Environment component for the scene, or undefined if no environment entity exists yet.

Mutate component.values directly to change skybox, fog, or gravity at runtime — EnvironmentSyncSystem picks up the changes next frame.

Returns ​

Environment | undefined

Example ​

ts
const env = this.world.getEnvironmentComponent();
if (env) {
  env.values.fog.type = "exponential";
  env.values.fog.exponential.density = 0.01;
}

getPostprocessingComponent() ​

ts
getPostprocessingComponent(): 
  | Postprocessing
  | undefined;

Defined in: World.ts:1611

Returns the singleton Postprocessing component for the scene, or undefined if no postprocessing entity exists yet.

Mutate component.values directly to enable/disable effects or tweak parameters at runtime — PostprocessingSyncSystem picks up the changes next frame.

Returns ​

| Postprocessing | undefined

Example ​

ts
const pp = this.world.getPostprocessingComponent();
if (pp) {
  pp.values.bloom.enabled = true;
  pp.values.bloom.intensity = 2.0;
}

raycast() ​

ts
raycast(
   origin, 
   direction, 
   near?, 
   far?, 
   options?): IntersectionResult[];

Defined in: World.ts:1660

Cast a ray from origin along direction and return every intersected entity-bound mesh, sorted by distance. Each result is a standard THREE.Intersection augmented with the owning entityId (or null if the hit object is not part of any tracked entity).

Big static meshes get a bounding volume hierarchy the first time a ray reaches them, so a ray at a 500k-triangle terrain tests a few dozen triangles. Pass options to make a call cheaper still:

  • firstHitOnly: only the nearest hit; meshes are tried nearest first and the search stops early. Use it whenever you only need "what's in front".
  • visibleOnly: skip hidden objects (three's raycaster tests them).
  • entities: test only these entities (and their children).
  • ignore: never hit these entities.
  • layers: only objects on these three.js layers.

Parameters ​

ParameterTypeDefault valueDescription
originVec3undefinedWorld-space origin of the ray (THREE.Vector3 or { x, y, z }).
directionVec3undefinedWorld-space direction of the ray. Will be normalized internally; magnitude is ignored.
nearnumber | RaycastOptions0Minimum hit distance, or the options object. Defaults to 0.
farnumberInfinityMaximum hit distance from the origin. Defaults to Infinity.
optionsRaycastOptions{}See above.

Returns ​

IntersectionResult[]

Example ​

ts
const hits = world.raycast(
  { x: 0, y: 1, z: 0 },
  { x: 0, y: 0, z: -1 },
);
if (hits[0]?.entityId !== null) {
  console.log("hit entity", hits[0].entityId, "at", hits[0].point);
}

// Only what's in front, ignoring hidden objects, within 50 m.
const [ground] = world.raycast(origin, down, {
  far: 50,
  firstHitOnly: true,
  visibleOnly: true,
});

raycastWith() ​

ts
raycastWith(raycaster, options?): IntersectionResult[];

Defined in: World.ts:1693

Like raycast, with a raycaster you set up yourself (for example with setFromCamera). Its near, far and layers are used; camera is filled in when missing, since three needs it to test sprites.

Parameters ​

ParameterType
raycasterRaycaster
optionsRaycastOptions

Returns ​

IntersectionResult[]


raycastFrom() ​

ts
raycastFrom(
   entityId, 
   near?, 
   far?): IntersectionResult[];

Defined in: World.ts:1758

Cast a ray from an entity's world-space position along its forward direction (the +Z axis of its world matrix). Returns intersected entity-bound meshes sorted by distance, with the source entity itself filtered out so the ray does not hit the caster.

Parameters ​

ParameterTypeDefault valueDescription
entityIdnumberundefinedEntity to cast the ray from. Must have an Object3DRef.
nearnumber | RaycastOptions0Minimum hit distance from the origin, or the options object (see raycast). Defaults to 0.
farnumberInfinityMaximum hit distance from the origin. Defaults to Infinity.

Returns ​

IntersectionResult[]

Example ​

ts
const hits = world.raycastFrom(this.entityId, 0, 50);
const closest = hits[0];
if (closest && closest.entityId !== null) {
  console.log("looking at", closest.entityId);
}

getEntityScript() ​

ts
getEntityScript<T>(entityId): T | null;

Defined in: World.ts:1836

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
entityIdnumber

Returns ​

T | null


getScripts() ​

ts
getScripts<T>(className): T[];

Defined in: World.ts:1849

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
classNamestring

Returns ​

T[]


getScript() ​

ts
getScript<T>(className): T | null;

Defined in: World.ts:1890

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
classNamestring

Returns ​

T | null


getAllEntities() ​

ts
getAllEntities(): WorldEntityView[];

Defined in: World.ts:1895

Returns ​

WorldEntityView[]


onSelectionChanged() ​

ts
onSelectionChanged(listener): () => void;

Defined in: World.ts:1901

Parameters ​

ParameterType
listenerSelectionListener

Returns ​

() => void


subscribe() ​

ts
subscribe(listener): () => void;

Defined in: World.ts:1909

Parameters ​

ParameterType
listenerStoreListener

Returns ​

() => void


onScriptError() ​

ts
onScriptError(listener): () => void;

Defined in: World.ts:1935

Listen for script errors from Behaviours and ScriptObjects: load failures, init() / build() / update() exceptions, and exceptions thrown inside Behaviour hooks such as onSelect or onUiPress.

Each DISTINCT error (same script URL, class, phase and message) is delivered once, so a script that throws every frame does not flood the listener. Returns an unsubscribe function.

Parameters ​

ParameterType
listenerScriptErrorListener

Returns ​

() => void

Example ​

ts
const stop = world.onScriptError((event) => {
  console.warn(`${event.className} failed in ${event.phase}: ${event.message}`);
});
// later
stop();

reportScriptError() ​

ts
reportScriptError(report, error): boolean;

Defined in: World.ts:1952

Report a script error. Used by the script systems and by any system that calls into Behaviour hooks; scripts themselves do not need to call it.

The first occurrence of a distinct error (same script URL, class, phase and message) is logged with console.error and delivered to onScriptError listeners; repeats are dropped. Returns true when the error was new.

Parameters ​

ParameterType
reportScriptErrorReport
errorunknown

Returns ​

boolean


clearScriptErrors() ​

ts
clearScriptErrors(scriptUrl?): void;

Defined in: World.ts:2004

Forget which script errors were already reported, so their next occurrence is logged and delivered again. Pass a script URL to forget only that script's errors (for example after hot-reloading it).

Parameters ​

ParameterType
scriptUrl?string

Returns ​

void


getDebugSnapshot() ​

ts
getDebugSnapshot(maxDepth?): unknown;

Defined in: World.ts:2016

Parameters ​

ParameterTypeDefault value
maxDepthnumber3

Returns ​

unknown


getDebugSignature() ​

ts
getDebugSignature(maxDepth?): string;

Defined in: World.ts:2066

Parameters ​

ParameterTypeDefault value
maxDepthnumber3

Returns ​

string


getEntitiesSnapshot() ​

ts
getEntitiesSnapshot(entityIds, maxDepth?): {
  entities: number[];
  components: {
     component: string;
     entries: {
        entityId: number;
        value: unknown;
     }[];
  }[];
};

Defined in: World.ts:2075

Serialize ONLY the given entities into the same columnar {entities, components} shape as getDebugSnapshot (no systems, no selection). Used by prefab/scene subtree serialization.

Parameters ​

ParameterTypeDefault value
entityIdsnumber[]undefined
maxDepthnumber10

Returns ​

ts
{
  entities: number[];
  components: {
     component: string;
     entries: {
        entityId: number;
        value: unknown;
     }[];
  }[];
}
NameTypeDefined in
entitiesnumber[]World.ts:2079
components{ component: string; entries: { entityId: number; value: unknown; }[]; }[]World.ts:2080

createHistorySnapshot() ​

ts
createHistorySnapshot(): WorldHistorySnapshot;

Defined in: World.ts:2117

Returns ​

WorldHistorySnapshot


applyHistorySnapshot() ​

ts
applyHistorySnapshot(snapshot): void;

Defined in: World.ts:2138

Parameters ​

ParameterType
snapshotWorldHistorySnapshot

Returns ​

void