Skip to content

Games and the loop ​

Three classes, one contract: a game is a function that returns an HTMLElement.

BaseGame ​

BaseGame owns what every scene needs: a WebGLRenderer (shadows enabled), a CSS2DRenderer label overlay, a PerspectiveCamera, OrbitControls, a Scene, an FPS stats widget, and a HUD. You rarely instantiate it directly — use one of its two subclasses.

Game — orbit scenes, no physics ​

For board games and display scenes: no physics world, no player.

ts
const game = new Game();
game.scene.add(...);
game.onFrame = (delta) => { /* per-frame animation */ };
const el = game.start(x, y, z);   // positions the camera, starts the loop

start(x, y, z) aims the camera at (x, 0, z) from a position derived from the arguments, installs the render loop and resize handler, and returns the container — with the HUD already attached. Orbit controls exist but you decide whether they're enabled.

FPS — physics worlds ​

new FPS() creates a Bullet dynamics world and arms the loading screen before any of your code can request an asset. Then:

  • fps.add(entity) / fps.remove(entity) — put entities in and out of the scene and the physics world (anything implementing registerPhysics/unregisterPhysics is wired in).
  • fps.start(player) — the playable form: ticks physics with a fixed 60 Hz step, updates every entity, dispatches collisions, renders.
  • fps.start({ camera }) — the same world watched through a fixed camera, for scenes where nobody walks (a demo reel, a menu background).
  • fps.pause() / fps.resume() — freeze and unfreeze simulation + entity updates (rendering continues). The loading gate uses this.

The physics step is budgeted: at most 2 substeps per frame and a capped delta, so an overloaded machine (or a backgrounded tab) degrades to slow motion instead of spiraling into a frozen catch-up loop.

Custom rendering hooks ​

All optional, all plain fields:

HookWhen to set it
onFrame(delta)per-frame game logic without owning the loop
renderFrame(scene, camera)route the frame through an EffectComposer (bloom, post)
viewCamerarender (and project CSS2D labels) through a different camera than the player's
onResizeHook(w, h)resize companion resources (a composer target, a HUD canvas)

Teardown ​

disposeGame(rootEl) looks up the game behind a container element (or any wrapper that contains one) and disposes it: stops the loop, removes every entity, frees the Bullet world and the WASM objects it owns. It is idempotent. Always call it when unmounting — the render loop does not stop on its own.