Engine
The Onceworlds engine is an optional library: 2D and 3D, physics, input, sound, UI and multiplayer in one package, with tests that play the game without a browser. Most games need only the platform guide and a web stack of their own. Start an engine project with npx @onceworlds/cli new my-game --engine, and read the kits for how a kind of game is wired. Every component and option is in the API reference.
Workflow
You are making an original game: its idea, look, feel and structure come from the creator's request and your design. The engine is a toolbox you reach into for what that design needs, never the shape of the game.
- Understand the ask: a whole game, or one step at a time? Either way, aim for a polished first version that impresses in its first minute: creators who aren't impressed leave.
- Design first in
DESIGN.md(onceworlds newwrites it): the hook and signature mechanic, the art direction, the feel, the first minute, and an originality pass: what it resembles (games, kits, recipes) and what makes it different. Topics:design,onboarding,ui-design. - Choose the foundation that serves the design, each first-class:
- Blank:
npx @onceworlds/cli new my-game(--space 3d): check, tests, the deploy workflow andDESIGN.mdwired, nothing else. Add only the modules the design needs. - A kit as a reference for plumbing (rooms, Flow, bots, tests): copy that, nothing visual ("Kits are references").
--kit <name>starts from one when the game really is that kind; its idea, look and screens are never yours. - The SDK alone, with any renderer or library (three.js, PixiJS, canvas, WebGL, from a CDN): https://onceworlds.com/agents.md.
- Blank:
- Build in vertical slices: the core action first, playable and in the game's look, then the first minute, then the rest.
Look up what you are not sure of (
onceworlds api,onceworlds recipe). - Check, look, polish.
npx @onceworlds/cli checkafter every change: lints with their fixes, the game's tests, simulated play through host reloads, drops, late joiners and garbage messages, and performance budgets. Thennpx @onceworlds/cli shot(--phase title|lobby,--poster cover,--storyfor the first minute) andserve(play it in a browser, offline, with bots): look as a new player would, and polish. - Publish:
npx @onceworlds/cli postersfor store art, then push to GitHub (its workflow deploys every push), or push a draft with the MCP tooldeploy_previewand publish it from the link it gives you.
Efficient, not lazy. Look-ups, recipes, kits and presets save tokens on plumbing: spend them on what makes this game itself. A preset, a library model or a kit's screen left in is a choice made on purpose, never a default.
With the onceworlds MCP tools, the same steps are new_game, api_lookup, recipe, check, screenshot, serve and deploy_preview.
Look things up
Each answer is a few lines, from the engine you have installed:
| Command (MCP tool) | Gives |
|---|---|
npx @onceworlds/cli api <name or words> (api_lookup) |
A signature, what it does, its fields or options and an example: api Shape2D, api "camera follow". --full: every field and member. |
npx @onceworlds/cli recipe [name] (recipe) |
Short, tested code for a kind of game (tycoon, survival, racing, party, rpg...) or a feature (chase-ai, inventory, shop...). |
npx @onceworlds/cli guide [topic] (read_guide with guide: "engine") |
A topic below, or any heading of this guide or the API reference. |
search_assets (MCP) |
Ready-made models, sprites, materials and sounds from the engine's library, with the code that uses each. |
| Topic | What it covers |
|---|---|
2d-looks |
Lights, shadows, hit flashes, outlines, glows, screen looks and shaders in 2D, one line each. |
assets |
Formats, loading and progress, art made in code, size and memory budgets. |
characters |
Players' own avatars if wanted (Humanoid, Avatar2D), NPCs, emotes, holding things, reaching. |
components |
Timer, AudioSource, UI nodes and AnimationPlayer: whole jobs from plain data. |
data |
Worlds kept between sessions (Persist) and values every server shares. |
debugging |
Why a game misbehaves: game.debug.text(), the F3 overlay, Build's Debugger. |
design |
What makes a game fun: the idea, originality, the first minute, strategy that reads, juice; the check before building. |
effects-3d |
Particles, trails, decals, words and sprites in 3D, and which for which moment. |
library |
Ready-made models, sprites, textures and sounds by name (Library.model), for blockouts and accents. |
lighting |
The time of day in one line (Environment), lamps, and baked light for phones. |
materials |
Looks in one line (rim, dissolve, hologram, wind...) and node-graph shaders. |
multiplayer |
Owners, replication, rpc and claims, the host as a page, shared time, rooms of 30. |
navigation |
Enemies, guards and bots that find their own way: NavAgent, bot orders, links. |
onboarding |
The goal and first move without reading, previews, cause and effect, strategy that reads, shot --story. |
platform |
What the platform requires and already does, and how the engine is hosted. |
posters |
Store art made by the game's own code (game.poster), and pictures to look at (shot). |
scenes |
Projects of scenes and scripts (what onceworlds.com/build makes), with a complete one. |
terrain |
Ground from presets or heights, solid with physics, sculpted in Build or in code. |
testing |
Headless tests with simulate, the chaos scenarios, and what check and doctor look at. |
ui-design |
Screens of the game's own, not the kit's: art direction, palette, type, a signature, Flow's screens restyled. |
water |
Water and lava, swimming, floating on the waves, and water that hurts. |
The same topics are at https://onceworlds.com/engine-guide/<topic>.md, and the whole reference at https://onceworlds.com/engine-api.md.
Rules
These are what break real games. check finds most of them in your code.
- Rules run in
fixedsystems withtime.dt(seconds per step) and seeded randomness,rng('name')in a system orworld.rng('name'): neverMath.random(),Date.now()orperformance.now()in a rule, and neversetTimeoutorsetIntervalfor gameplay (use aTimeror counttime.dt). Every page, a reload and a new host must agree. - The host decides what matters. Systems that change shared state have
authority: 'host'; things the host owns are spawned with{ owner: 'host' }; a component a player must not write (health, score) hasnet: { owner: 'host' }. A player asks the host withnet.rpc(its arguments are checked against a schema) ornet.claim(contested things), never by writing the result. - Only the engine touches the page. Systems never use
documentorwindow; screens areui.viewand Flow's; HTML isui.overlay.el('span', { text })(neverinnerHTML: text from players is untrusted). Games never import three.js or Rapier:Render3D,Mesh,Physics3Dand the rest are the way in. - Every action works on a phone. Each
Input.buttonhastouch: { label }, eachInput.axis2dhasstick: true; at most four buttons and a stick."controls"inonceworlds.jsonis the menu's "How to play" (npx @onceworlds/cli doctor --fixwrites it from the action map). - The platform's server and lobby. It picks the server and has invites, chat and volume: build none of those. A lobby follows
its rule (everyone readies up, a host starts private ones, joining never starts a match) with one countdown: Flow's shells
(
rounds,turns,coop,dropIn) do it all in your look (UI({ flowViews }));Flow.none()leaves the structure to you. - Keep it bounded. Despawn what you spawn (bullets, particles, pickups) or cap it; no loop without an end; a file under about 1,500 lines; images and sounds compressed.
- Saves go through
defineSaveandSave, neverlocalStorage(the game frame forgets it on reload).alert,confirm,prompt, popups and navigation are blocked in the game frame. - Readable at a glance. Text at least 18 px on a phone and in strong contrast with what is behind it; buttons at least 56 px.
The files
index.html loads main.js as a module; nothing else is needed
main.js import { createGame } from '@onceworlds/engine'; import { config } from './game.config.js'; createGame(config).start();
game.config.js export const config = { modules, systems, scene }; export const actions = { ... }; export const quick = ...
src/ or *.js components, systems, prefabs, UI views, bots
test/*.test.js headless tests with @onceworlds/engine/test (never deployed)
store/ icon and thumbnails (made by `posters`)
onceworlds.json { "slug", "name", "description", "engine": "1", "genre", "icon", "thumbnails", "controls", "badges" }
game.config.js has no side effects: the tests and check play what main.js starts. A game of matches exports quick (one
short round, short screens) for check to play to its results. "engine": "1" makes the platform provide the newest 1.x engine:
write no import map of your own.
Kits are references
Each kit is a complete game of one kind, written to be read. Take the plumbing your design needs (how rooms, Flow, bots and tests
are wired) and nothing visual: its idea, rules, numbers, look and screens are its own. Recipes (npx @onceworlds/cli recipe) are the
same for a feature or a kind of game.
| Plumbing worth reading | Kit | Built with |
|---|---|---|
| Real-time movement and hits, a camera fitted to an arena, bots that fight | arena-2d |
Render2D, Physics2D, TopDown, Flow.rounds |
| Jumping, a level from a text map, a race to a flag | platformer-2d |
Physics2D, Platformer2D, CameraRig.sideScroll |
| Many players, short rounds one rule decides, no physics | party-2d |
Render2D, Intent, Flow.rounds |
| A 3D character, a follow camera, dashing into rivals | third-person-3d |
Render3D, Humanoid, Character3D, CameraRig.thirdPerson |
| Vehicles, laps, terrain, bots that drive | racing-3d |
Physics3D, ArcadeVehicle, Terrain3D, Flow.rounds |
| Turns, a grid with paths and ranges, an isometric board | tactics-iso |
Grid, GridMover, Flow.turns |
The APIs you use most
import { createGame, defineComponent, defineSystem, t, Transform, Timer } from '@onceworlds/engine';
import { Render2D, Shape2D, Text, camera2D, Input, Audio, UI, Feel, Net, Flow } from '@onceworlds/engine/modules';
const Coin = defineComponent('Coin', { value: t.u8(1) }, { net: { replicate: true } });
export const actions = {
move: Input.axis2d({ keys: 'wasd arrows', stick: true, pad: 'left', label: 'Move' }),
dash: Input.button({ keys: 'Space', pad: 'A', touch: { label: 'Dash', big: true }, label: 'Dash' }),
};
const Collect = defineSystem({
name: 'collect',
stage: 'fixed', // 60 times a second: rules go here, with time.dt
query: [Coin, Transform],
authority: 'host', // only the host's page decides
run({ query, world, feel, audio }) { /* ... */ },
});
export const config = {
space: '2d',
modules: [Render2D(), Input({ actions }), Audio(), UI(), Feel(), Net({ components: [Coin] }), Flow.rounds({ /* title, lobby, roster, round, scoring */ })],
systems: [Collect],
scene(world) { world.spawn([Transform(), camera2D({ height: 12, clear: '#10131c' })]); },
};
| Doing | With |
|---|---|
| Data and rules | defineComponent(name, { field: t.f32(0) }), defineSystem({ name, stage, query, authority, run }), defineEvent |
| Entities | world.spawn([Transform(), ...], { owner }), entity.get(Health), entity.has(Health), world.despawn(e), world.query([...]).each(...): its views are one object moved along, so keep the entity, never a view |
| Time and chance | time.dt, time.match, rng('loot').int(1, 6), Timer({ waitTime: 2, autostart: true }) and TimerTimeout |
| 2D | Render2D(), camera2D({ height }), Shape2D, Sprite, Text, CameraRig.follow |
| 3D | Render3D(), Environment.preset('afternoon') (sky, sun, haze), Mesh.box(size, Material.standard({ color })), Library.model('tree.pine'), PostFx.polished(), CameraRig.thirdPerson |
| Moving | Physics2D(), Body2D.dynamic(), Collider2D.box({ size }), Controllers(), Intent, TopDown, Platformer2D, Character3D, ArcadeVehicle, physics.raycast |
| Finding the way | NavAgent.chase('players'), NavAgent.patrol(points), ctx.chase(target) in a bot's think (the navigation topic) |
| Input | Input({ actions }), input.axis('move'), input.held('jump'), input.pressed('dash'), input.pointer('point') |
| Tap to world | 2D render2d.screenToWorld(p.x, p.y, out); 3D render3d.screenToRay(p.x, p.y, ray), then physics.raycast(ray.origin, ray.direction, 100) |
| Feel and sound | feel.shake(0.4), feel.squash(e), feel.particles.burst('sparks', e) and feel.floatText('+3', e) (2D and 3D), feel.tween(e, Transform, { scale: 1.3 }), audio.play('coin'); in 3D Particles3D, Trail3D (the effects-3d topic) |
| Screens | UI({ theme, flowViews }) (Flow's screens, your look), ui.view(name, build), ui.draw.text, NameTag |
| Multiplayer | Net({ components }), net.rpc(name, { args, run }), net.claim, net: { owner: 'host' } |
| The match | Flow.rounds({ round: { isOver, rank }, roster: { fill }, scoring }), Flow.placePoints, Flow.sumPoints (points add up), Flow.dropIn(), Flow.turns, Flow.none() (a structure of your own), defineBotSystem |
| Progress | defineSave('Profile', { wins: t.u32() }), Save(Profile); Persist() keeps a server's world (the data topic) |
| Tests and art | simulate(config, { humans, bots, chaos }) from '@onceworlds/engine/test', game.poster('cover', setup) |
Go a layer down when the design asks
Every ready-made piece has a lower layer, the same API it is written with. Going down for a feel, a look or a structure the top doesn't give is craft, not a detour.
| You need | Quick | Down to |
|---|---|---|
| A controller that feels different | Platformer2D, TopDown, Character3D, ArcadeVehicle with their options |
write a system that reads Intent and calls physics.moveCharacter(entity, desired); then raw Body2D / Body3D velocities and applyImpulse |
| A look no preset gives | Material.standard/toon/unlit and the looks (Material.rim...), PostFx.polished(), Environment |
Material.shader, your own lights and sky, PostFx({ passes }), then render.addPass (2D) or render3d.addPass (3D) |
| Art of the game's own | Library models and sprites, Shape2D, Mesh |
pictures and models made for it (Sprite, glTF), drawn or generated in code |
| Your own screens | Flow's screens with your look: UI({ theme, flowViews }) |
replace a view by its name, then ui.draw.*, then ui.overlay HTML |
| Rules of who owns what | Net({ components }), owner: 'host', rpc, claim |
net.send and net.onMessage with your own validated messages |
| A structure of your own | Flow.rounds, .turns, .dropIn, .coop with their options |
Flow.none(), and room.startMatch and endMatch yourself (or no match at all), following the platform guide's "Matches" |
| A sound that isn't there | Audio synthesized effects, audio.play(name), buses |
the Web Audio graph through audio.context |
| More than the engine does | everything above | window.onceworlds (the SDK) beside the engine; read https://onceworlds.com/agents.md |
Make it fun
Players leave in seconds if they don't get it. These hold whatever the game is (the design topic has more):
- Graspable in one look: the goal and the first move clear without reading, and a name that says what you do. A familiar rule is one way there; an original idea needs the same clarity.
- Playing within 10 seconds: show the goal (an arrow, a glowing target) instead of explaining it.
- Always know the goal and how you're doing from the screen; the next game one tap away.
- Never alone: a lone player still gets the game. Bots fill a match's seats (
roster: { fill },botProfile(skill): like people, never perfect), or the world is fun solo. - Every action answers within a tenth of a second with a sound and motion:
feel.squash,feel.particles.burst,feel.floatText, eased tweens,feel.shake(the camera, never the body). - A look of its own: an art direction from the game's world (palette, type, materials, art made for it, one signature
element), every screen in it (
ui-designtopic). Presets and the library are a quick start, not a style. - Readable: preview what a move will do, show what caused each result, teach in the first moments (
onboardingtopic).
Multiplayer with the engine
world.spawn([...], { owner: me.id })makes a player's page simulate it;{ owner: 'host' }is for the host's rules (bots, pickups, a ball), which carry on under the next host when it reloads, drops or leaves (checkplays exactly that). Replicate only what others must see (net: { replicate: true }), withpredict: trueon the owner's movement.- Actions are calls:
net.rpc('fire', { args: { angle: t.f32() }, to: 'host', rate: 10, run })checks its arguments and how often a player may call. Never trust a client's word about damage, score, someone else's position or time. - Only replicated components cross the network. Looks, colliders, bodies and controllers are added on every page by a system that
finds what lacks them (
query: [Player, { without: [Shape2D] }]), with a body and a controller only wherenet.simulates(entity).
More: Multiplayer with the engine
Test it without a browser
// test/match.test.js
import { simulate } from '@onceworlds/engine/test';
import { expect, test } from 'vitest';
import { config } from '../game.config.js';
test('a full match ends with everyone ranked, through a reloaded host and a dropped player', async () => {
const run = await simulate(config, { humans: 2, bots: 2, seed: 7, minutes: 3, chaos: ['reload-host', 'drop-player'], latency: [10, 60] });
expect(run.errors).toEqual([]);
expect(run.ranking).toHaveLength(4);
});
Test the rules, not the pixels: step the game (game.run(seconds)), drive input (input.setAxis('move', 1, 0), input.tap('jump'))
and assert on components. The testing topic has the chaos scenarios, the lints and the budgets.
More: Test it without a browser
Mistakes the engine's errors will tell you about
The errors say what went wrong, where, and the line that fixes it. The usual ones:
| You wrote | What to do |
|---|---|
import ... from '@onceworlds/engine' and the deploy is refused |
"engine": "1" in onceworlds.json |
world.spawn([Health]) |
components are called: Health() or Health({ hp: 5 }) |
a system that changes physics bodies in update |
do it in fixed, before 'physics2d' / 'physics3d' |
| a second lobby or 3-2-1 beside Flow's | one of each: Flow's in your look (UI({ flowViews })), or Flow.none() and the platform's |
| touch controls drawn by hand | Input({ actions }) sets the platform's; branch on input.device, not on screen size |
| a message handler that trusts its input | use rpc or claim (schema checked), or validate every field |
Gotchas found while building the kits
More for multiplayer are in the multiplayer topic.
input.axis('move').yis -1 for up, like the platform's stick; a 2D world's y points up: flip it when you move.- An entity this page just spawned has no
net.owneruntil its first frame ends: decide "is it mine" from its data. Spawn host-owned things once in a room (round.populate, or behindflow.phase === 'playing'): before the join every page is the host. - In a module's
install,game.worlddoesn't exist yet: read it ininitor in what you register.physicsbelongs to a world: use it in a system. - The roster's bots carry the
Botcomponent: list it inNet({ components: [..., Bot] }). - A staged poster is
flow.phase === 'playing'too: rules of play checkflow.posterand return (theposterstopic). Input.pointer({ drag: 'none' })never reports presses: use the default drag mode, or a button action, for taps.- Moving platforms and doors are kinematic bodies moved by their Transform; characters ride them (and each other) by themselves.