Tutorial 2 — Components & archetypes¶
Outcome: you’ll see how component sets automatically form archetypes (tables), and how entities “move” between them when you add() / remove() components—without digging into internals. Archetypes store data in SoA (one column per component type).
1) Define a few component types¶
Create tutorial2.ts:
1 2 3 4 5 6 |
The ECS uses component constructors as the “type key”, and archetypes store entities in SoA tables.
2) Create a World and spawn entities with different component sets¶
3) Add a tiny helper to “see” matches¶
We can’t (and don’t need to) access archetype tables directly. Instead, we observe which queries match, before and after structural changes.
The query API yields { e, c1, c2, ... } rows in the order you request components.
4) Observe the “automatic archetypes” effect¶
Add this and run once:
You’ll see (by IDs) that:
e1matchesPositiononlye2matches bothPositionandPos+Vele3matchesHealthonly
What this demonstrates: entities with the same component set are stored together (same archetype). Archetypes are created implicitly as you introduce new component combinations.
5) Make an entity “move” between archetypes (add)¶
Now add a component to e1:
You should see:
e1now appears inVelocity- and also in
Pos+Vel
Why: add() is a structural change that can move an entity into a different archetype table (because its component set changed).
6) Make an entity “move” between archetypes (remove)¶
Now remove Position from e2:
You should see:
e2disappears fromPositionandPos+Vele2still appears inVelocity
Again: remove() is structural and can move the entity to a new archetype.
7) Run it¶
What you just learned (by doing)¶
- Components are plain data types (classes).
- Archetypes (tables) are created automatically for each distinct component set, stored in SoA layout.
- When you
add()/remove()components, entities “move” because their component set changes (structural change).
Note for later tutorials: structural changes can be unsafe while iterating; that’s why
cmd()+flush()exist.