Game loop, input and physics · 5 MIN READ
Entities as IDs, components in dense generic stores, systems as plain loops
Build a minimal entity-component store with generics, run systems over dense slices, remove with swap-delete, and judge when plain structs are the better design.
The first instinct for game objects is a hierarchy: a base object, a character built on it, an enemy built on that. In Go such hierarchies fight the language, which has no inheritance, and the hardware, which prefers contiguous data. An entity-component design keeps an entity as a bare ID, stores each component type in its own dense slice, and writes behavior as systems that loop over those slices.
gamedev · A MAP OF THE IDEA
- Spawn an entity ID
- Add components to stores
- Systems loop over dense data
- Flush queued removals
Useful when
- Behavior composes from components without type hierarchies.
- Systems iterate contiguous slices with no gaps.
Watch out
- Component pointers are invalid after the next Add or Remove.
- Recycled IDs need generation counters to reject stale handles.
Implementation & operation cost: A store type and explicit world fields; more indirection than plain structs, worth it only when composition or measured iteration cost demands it.
Why deep object hierarchies hurt
Picture GameObject, Character embedding GameObject, Enemy embedding Character and FlyingEnemy embedding Enemy. Embedding promotes methods but is not inheritance: there is no virtual dispatch from the embedded type back to the outer one, so when a Character method calls Update it calls Character's Update, never FlyingEnemy's. Teams compensate with interfaces at every level and type switches, while the base type collects fields that only some objects use. Behavior that cuts across branches, such as a turret that has health but is not a character, has no natural home. Iteration suffers as well: a slice of interface values points at objects scattered across the heap, so updating ten thousand of them chases ten thousand pointers. Composition fixes both problems: an entity has whichever components it has, and each system names the ones it needs.
A sparse set per component type
Store[T] keeps the components of one type in a dense slice, the owning entity of each element in a parallel owners slice, and a sparse slice from entity ID to dense index plus one, so that zero means absent. Add and Get take constant time, iteration visits only entities that have the component with no gaps, and Remove swap-deletes: the last element moves into the hole, so removal is constant time and the data stays dense. World has one typed store field per component, which keeps every access checked by the compiler without reflection or maps keyed by type. Systems are ordinary functions over the world.
package main
import (
"fmt"
"iter"
"slices"
)
// Entity is only an ID. It owns no data and has no methods of its own.
type Entity uint32
// Store packs one component type densely. sparse[e] holds the dense index
// plus one (zero means absent); owners[i] says which entity owns data[i].
type Store[T any] struct {
sparse []int
owners []Entity
data []T
}
func (s *Store[T]) Has(e Entity) bool { return int(e) < len(s.sparse) && s.sparse[e] != 0 }
func (s *Store[T]) Add(e Entity, v T) {
if s.Has(e) {
s.data[s.sparse[e]-1] = v
return
}
if need := int(e) + 1; need > len(s.sparse) {
s.sparse = append(s.sparse, make([]int, need-len(s.sparse))...)
}
s.data = append(s.data, v)
s.owners = append(s.owners, e)
s.sparse[e] = len(s.data)
}
// Get returns a pointer into the dense slice, valid until the next Add or Remove.
func (s *Store[T]) Get(e Entity) (*T, bool) {
if !s.Has(e) {
return nil, false
}
return &s.data[s.sparse[e]-1], true
}
// Remove swap-deletes: the last element moves into the hole, so order changes.
func (s *Store[T]) Remove(e Entity) {
if !s.Has(e) {
return
}
i, last := s.sparse[e]-1, len(s.data)-1
s.data[i], s.owners[i] = s.data[last], s.owners[last]
s.sparse[s.owners[i]] = i + 1
var zero T
s.data[last] = zero // do not keep references alive in the unused tail
s.data, s.owners = s.data[:last], s.owners[:last]
s.sparse[e] = 0
}
// All yields entities and component pointers in dense order. Do not Add or
// Remove while iterating; queue structural changes instead.
func (s *Store[T]) All() iter.Seq2[Entity, *T] {
return func(yield func(Entity, *T) bool) {
for i := range s.data {
if !yield(s.owners[i], &s.data[i]) {
return
}
}
}
}
type Position struct{ X, Y int }
type Velocity struct{ X, Y int }
type Lifetime struct{ Ticks int }
type World struct {
last Entity
Pos Store[Position]
Vel Store[Velocity]
Life Store[Lifetime]
dead []Entity
}
func (w *World) Spawn() Entity { w.last++; return w.last }
func (w *World) Destroy(e Entity) {
w.Pos.Remove(e)
w.Vel.Remove(e)
w.Life.Remove(e)
}
// Movement touches every entity that has both Position and Velocity.
func Movement(w *World) {
for e, v := range w.Vel.All() {
if p, ok := w.Pos.Get(e); ok {
p.X += v.X
p.Y += v.Y
}
}
}
// Aging only queues deaths; Flush applies them after all systems ran.
func Aging(w *World) {
for e, l := range w.Life.All() {
l.Ticks--
if l.Ticks == 0 {
w.dead = append(w.dead, e)
}
}
}
func Flush(w *World) []Entity {
gone := slices.Clone(w.dead)
for _, e := range w.dead {
w.Destroy(e)
}
w.dead = w.dead[:0]
return gone
}
func main() {
w := &World{}
player := w.Spawn()
w.Pos.Add(player, Position{0, 0})
w.Vel.Add(player, Velocity{1, 0})
tree := w.Spawn() // Position only: systems that need Velocity skip it
w.Pos.Add(tree, Position{5, 5})
for i, ticks := range []int{2, 1, 3, 5} {
b := w.Spawn()
w.Pos.Add(b, Position{0, i})
w.Vel.Add(b, Velocity{3, 0})
w.Life.Add(b, Lifetime{ticks})
}
fmt.Println("tick 0: velocity dense order", w.Vel.owners)
for tick := 1; tick <= 3; tick++ {
Movement(w)
Aging(w)
gone := Flush(w)
fmt.Printf("tick %d: destroyed %v, velocity dense order %v\n", tick, gone, w.Vel.owners)
}
ids := slices.Clone(w.Pos.owners)
slices.Sort(ids) // dense order is an implementation detail; report by ID
for _, e := range ids {
p, _ := w.Pos.Get(e)
_, moving := w.Vel.Get(e)
fmt.Printf("entity %d at (%d, %d) moving=%t\n", e, p.X, p.Y, moving)
}
}Entity 1 is a player with Position and Velocity, entity 2 a tree with Position only, and entities 3 to 6 are bullets that live 2, 1, 3 and 5 ticks. Movement ranges over the velocity store, so the tree is never visited. On tick 1 bullet 4 dies and bullet 6, the last element, moves into its slot, giving the dense order [1 3 6 5]; every later death swaps again. Aging only queues deaths in w.dead and Flush destroys them after the systems finish, because removing from a store while ranging over it would skip the element swapped into the current slot. The final report sorts by ID because dense order is an implementation detail.
Rules that keep a store correct
Get returns a pointer into the dense slice, which is fast but short-lived: the next Add may reallocate the slice and the next Remove may move another entity's data to that address. Use such a pointer within one system and never keep it. All is a range-over-func iterator of type iter.Seq2, and the same rule applies to it: no structural changes while iterating, which is why destruction is queued. Remove zeroes the vacated tail element, so a component holding a pointer, such as a sprite, does not keep it alive. This model never reuses IDs; a real engine recycles them and pairs each index with a generation counter, so a stale handle to a destroyed entity fails the lookup instead of silently addressing whichever entity inherited its slot. Rendering usually needs its own sort by layer or depth, because swap-delete makes storage order unstable.
When plain structs are enough
Most small Go games need none of this. With a player, a few enemy kinds and bullets, one slice of plain structs per kind and an update loop is already contiguous, fully typed and easy to debug. Reach for components when the same behavior must apply to many otherwise unrelated kinds, when designers compose entities from data files, or when a profile shows iteration dominating the tick; decide with a benchmark, not on principle. Full ECS libraries add archetype storage, queries over several components and parallel scheduling, and each of those is real complexity to own.
type Bullet struct {
Pos, Vel Vec2
Ticks int
}
func updateBullets(bs []Bullet) []Bullet {
for i := range bs {
bs[i].Pos = bs[i].Pos.Add(bs[i].Vel)
bs[i].Ticks--
}
return slices.DeleteFunc(bs, func(b Bullet) bool { return b.Ticks <= 0 })
}This fragment reuses Vec2 from the movement lesson and is not compiled here. One contiguous slice and one loop, with no IDs at all: for a few hundred bullets it is the simplest option and likely the fastest. slices.DeleteFunc keeps the survivors in order and, since Go 1.22, zeroes the elements past the new length, so removed bullets release anything they referenced.
Test the invariants, not just the output
A sparse set has invariants a short test can check after every operation: for each dense index i, sparse[owners[i]] equals i + 1; the number of non-zero sparse entries equals len(data); and owners and data have the same length. Drive random sequences of Add and Remove from a seeded generator and check the invariants after each step, and you will catch the classic swap-delete bug of clearing the removed entity's sparse entry but forgetting to update the moved one. For systems, assert on results keyed by entity ID, never on dense order, so legitimate storage changes do not break the tests.
TAKE THIS WITH YOU
Keep entities as IDs and components in dense per-type stores, queue structural changes until the systems finish, never hold component pointers across ticks, and stay with plain struct slices until composition or a profile justifies components.
Check your understanding
Why does the Aging system queue dead entities instead of removing them while it ranges over the store?
Go to the source
Progress stays in this browser. No account needed.