{"article":{"slug":"making-games-in-go-entity-component-system-ecs","title":"Making Games in Go: Entity Component System (ECS)","subtitle":null,"summary":"Miłosz Smółka of Three Dots Labs walks through the Entity Component System pattern for 2D games in Go using the Donburi library, from entities and systems to archetypes, events, and a fuller pufferfish game example.","content_type":"tutorial","language":"en","canonical_url":"https://threedots.tech/post/making-games-in-go-ecs/","author":{"name":"Miłosz Smółka","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Three Dots Labs","url":"https://threedots.tech/","listing_slug":null,"listing":null},"topics":[{"name":"tutorials","slug":"tutorials","url":"https://listedarticles.com/topics/tutorials"},{"name":"programming","slug":"programming","url":"https://listedarticles.com/topics/programming"},{"name":"programming-languages","slug":"programming-languages","url":"https://listedarticles.com/topics/programming-languages"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":6616,"reading_minutes":29,"published_at":"2026-11-16T23:00:00.000Z","added_at":"2026-11-17T19:52:54.492Z","updated_at":"2026-11-17T19:52:54.492Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/making-games-in-go-entity-component-system-ecs","markdown_url":"https://listedarticles.com/articles/making-games-in-go-entity-component-system-ecs.md","example":false,"citation":"Miłosz Smółka, Three Dots Labs. \"Making Games in Go: Entity Component System (ECS).\" 16 Nov 2026. https://threedots.tech/post/making-games-in-go-ecs/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://threedots.tech/post/making-games-in-go-ecs/"},"body_markdown":"Even if you use AI, it’s still worth learning the foundations. I found it easier to steer agents when they work on a project where I had already put the scaffolding in place. They’re much better at imitation than coming up with something new. (I share the patterns I give agents [at the end](#making-games-with-ai-agents).)\n\n**Learning software concepts isn’t only about the code. It also changes how you think about projects.** You know what systems are in place, how the elements interact, and what a good solution would be. I care more than ever about keeping my mental models sharp now that AI can produce infinite output that’s worthless unless someone decides otherwise.\n\nNote\n\nThe usual disclaimer: I’m a hobbyist making [tiny 2D games](https://github.com/m110/). I do it for fun, and have never shipped a professional game. I write about what has worked for me, and it could be something dumb. (If that’s the case, let me know in the comments!)\n\n## Why bother with ECS?\n\n[Previously](https://threedots.tech/post/making-games-in-go/), I described a simple approach to working with game objects. Each object is a struct and has its own `Update()` and `Draw()` methods. In the game loop, we iterate over all the objects and call their methods.\n\n```\ntype Player struct {\n\tPosition Vector\n\tSprite   *ebiten.Image\n}\n\nfunc NewPlayer() *Player {\n\treturn &Player{\n\t\tPosition: Vector{\n\t\t\tX: 100,\n\t\t\tY: 100,\n\t\t},\n\t\tSprite:   PlayerSprite,\n\t}\n}\n\nfunc (p *Player) Update() {\n\tp.Position.X += 10\n}\n\nfunc (p *Player) Draw(screen *ebiten.Image) {\n\top := &ebiten.DrawImageOptions{}\n\top.GeoM.Translate(p.Position.X, p.Position.Y)\n\tscreen.DrawImage(p.Sprite, op)\n}\n```\n\nThis is a good start. It’s easy to follow how the game works and to add new objects. But as the game becomes more complex, it gets messy. The `Update` methods get long. You need to pass many references around, because objects don’t know about other objects. Some logic doesn’t clearly belong to any one object.\n\nAnother challenge in many games is that objects have similar traits, but aren’t quite the same thing. For example, a player character, an NPC, and an enemy are very similar objects, but also completely different gameplay-wise. They all have health points, move in the game world, collide with the terrain, and so on. But one is controlled by the player, one you can talk to to accept a quest, and one attacks you on sight.\n\nOne way to approach this is with some kind of inheritance (or embedding in Go). You create a basic `Object` with all common traits, then extend it with more specific entities.\n\n![A base Entity type with Player, NPC, and Enemy types built on top of it](https://threedots.tech/post/making-games-in-go-ecs/images/inheritance_hubc71d098305ed46df1b16520ffa98065_56195_697x562_fill_q80_h2_lanczos_smart1_3.webp)\n\nBut what if you want an NPC to turn hostile after an interaction? Or if you want the player to sometimes talk to the enemy? Or if you want to briefly take control over any of them? The inheritance model stops working, and you need workarounds that can get ugly.\n\nI’ve been trying to figure this out, and I discovered the Entity Component System (ECS) architecture. It became my go-to approach for making games. I’m using the [Donburi](https://github.com/yohamta0/donburi-ecs) ECS library in Go together with the [Ebitengine](https://ebitengine.org) 2D game engine. Both are super fun to work with.\n\nYou may see ECS mentioned for performance reasons (storing components of one type together in memory makes iterating over them fast), but for me, **the best part is the mental model shift**. You split the game into small building blocks with clear responsibilities, so it’s easier to think about how it works. Keeping the data separate from the behavior is also an interesting idea that can help you approach other software projects.\n\n## Entities, components, and systems\n\nNote\n\nIf you want to follow along, I recommend reading [the previous post](https://threedots.tech/post/making-games-in-go/) first, where I explain the basics of Ebitengine.\n\nIn ECS, you split your game into three parts:\n\n- **Entities:** generic “objects” that appear in your game. They have no behavior on their own, no dedicated structs, and no `Update` or `Draw` methods. An entity on its own is essentially an ID. It’s a unique thing that exists in the game.\n- **Components:** plain data structs that you’ll attach to the entities. They describe whatever attributes the entity has. For example: position, health points, velocity, etc. They’re like building blocks that make up each entity.\n- **Systems:** the actual game logic. `Update` loops that do something with the entities with specific components on them.\n\nIt’s like an extreme take on the Single Responsibility Principle. You clearly separate identity, data, and behavior in the code.\n\n![Plain game objects, each with its own Render and Update, compared to ECS entities made of components and processed by separate systems](https://threedots.tech/post/making-games-in-go-ecs/images/objects-vs-ecs_hu0548950b3e9d82c5977c95875605d4b6_334498_1988x1226_fill_q80_h2_lanczos_smart1_3.webp)\n\nLet’s consider a trivial example to see how it works. We’ll display a grid of colorful tiles on the screen.\n\n![A grid of colorful square tiles](https://threedots.tech/post/making-games-in-go-ecs/images/tiles_hu32d8dd9b5124023c269320e0f62f673a_571384_2272x2208_fill_q80_h2_lanczos_smart1_3.webp)\n\nEach tile is an entity. An entity has no attributes by itself. Our game has 240 tiles. To give them meaning, we need to add components to them.\n\nLet’s think of a minimal set of components the entity needs to appear as a tile on the screen.\n\nWithout a doubt, it needs a position in the game world, a pair of `X` and `Y` coordinates:\n\n```\ntype PositionData struct {\n\tX float64\n\tY float64\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L9)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L9)\n\nThe other thing is the tile’s color. That’s a separate component:\n\n```\ntype ColorData struct {\n\tColor color.Color\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L22)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L22)\n\nNow, it would be natural to represent the tile like this:\n\n```\ntype Tile struct {\n\tPosition PositionData\n\tColor    ColorData\n}\n```\n\nBut **this isn’t what we want.** As strange as it sounds, our game shouldn’t have a `Tile` struct. In ECS, there’s no place for a dedicated `Tile` type. Instead, we have *generic* entities made of components.\n\n![A tile entity made of a Position and a Color component](https://threedots.tech/post/making-games-in-go-ecs/images/tile-components_hu27e00c1b867f93ef1cec5dc19722974c_92402_1772x658_fill_q80_h2_lanczos_smart1_3.webp)\n\n### Working with Donburi\n\nLet’s start working with Donburi primitives.\n\nThe structs we created above (`PositionData` and `ColorData`) hold the components’ *data*. We need to register component types as well. These are global variables:\n\n```\nimport \"github.com/yohamta/donburi\"\n\nvar (\n\tPosition = donburi.NewComponentType[PositionData]()\n\tColor    = donburi.NewComponentType[ColorData]()\n)\n```\n\nTo create an entity, we first have to create a *world*. It’s where Donburi tracks entities. Our game will have a single world with all entities living inside.\n\n```\nworld := donburi.NewWorld()\n```\n\nWe create an entity for the tile with two components:\n\n```\nentity := world.Create(Position, Color)\n```\n\nThe entity lives inside the world from now on. We don’t need to keep track of it. `Create` returns an integer, because the entity is just an ID.\n\nIf we want to interact with the entity, we need to get its *entry* from the world:\n\n```\nentry := world.Entry(entity)\n```\n\nThe entry is a regular Go pointer, and it lets you do something useful with the entity, like reading or setting its component data.\n\nAt this point, the entity has two components attached: `Position` and `Color` (because we passed them to `world.Create()`). They hold zero values of their data structs.\n\nWe can read their data with the component’s `Get` method. This may be a bit unusual at first, since we call a method on the global component type, not directly on the entry.\n\n```\npos := Position.Get(entry)\ncolor := Color.Get(entry)\n\n// pos.X == 0\n```\n\nTo set a value, we can use `SetValue` like this:\n\n```\nPosition.SetValue(entry, PositionData{\n\tX: 100,\n\tY: -50,\n})\n```\n\nOr by changing the struct in place, since `Get` returns a pointer:\n\n```\npos := Position.Get(entry)\npos.X += 10\n```\n\nWe can also add or remove components and check if they exist:\n\n```\nif entry.HasComponent(Color) {\n\tentry.RemoveComponent(Color)\n}\n\nentry.AddComponent(Color)\n```\n\n### Introducing systems\n\nThe last part we need is systems. They are similar to regular `Update` functions.\n\nAs a reminder, here’s a minimal Ebitengine game (I’m skipping the `Layout` method, which isn’t relevant). `Update` is called every *tick*, usually 60 times per second, and `Draw` is called every *frame*.\n\n```\ntype Game struct {}\n\nfunc (g *Game) Update() error {\n\treturn nil\n}\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n\n}\n```\n\nIn ECS, we move all the code from `Update()` and `Draw()` into systems. While Donburi has an experimental systems feature, I’ll stick to a manual but simpler approach here.\n\nA *system* is an `Update` function that works within a given `world`.\n\n```\ntype System interface {\n\tUpdate(w donburi.World)\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/main.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L24)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L24)\n\nWe keep the world and a slice of systems in the `Game` struct. Then, we iterate over the systems in the `Update` method. Each tick, we update every system in the game.\n\n```\ntype Game struct {\n\tworld   donburi.World\n\tsystems []System\n}\n\nfunc (g *Game) Update() error {\n\tfor _, s := range g.systems {\n\t\ts.Update(g.world)\n\t}\n\n\treturn nil\n}\n```\n\nWe’ll also keep systems for drawing on the screen. I’ll call this kind of a system a `Drawer`, following the Go convention:\n\n```\ntype Drawer interface {\n\tDraw(w donburi.World, screen *ebiten.Image)\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/main.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L28)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L28)\n\nNote that a single system could expose both the `Update` and `Draw` methods.\n\nA complete game could look like this:\n\n```\ntype Game struct {\n\tworld   donburi.World\n\tsystems []System\n\tdrawers []Drawer\n}\n\nfunc NewGame() *Game {\n\treturn &Game{\n\t\tworld: createWorld(),\n\t\tsystems: []System{\n\t\t\tNewClickSystem(),\n\t\t\tNewVelocitySystem(),\n\t\t},\n\t\tdrawers: []Drawer{\n\t\t\tNewRenderingSystem(),\n\t\t},\n\t}\n}\n\nfunc (g *Game) Update() error {\n\tfor _, s := range g.systems {\n\t\ts.Update(g.world)\n\t}\n\n\treturn nil\n}\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n\tfor _, d := range g.drawers {\n\t\td.Draw(g.world, screen)\n\t}\n}\n\nfunc createWorld() donburi.World {\n\tworld := donburi.NewWorld()\n\n\ttile := world.Create(Position, Color)\n\ttileEntry := world.Entry(tile)\n\tPosition.Get(tileEntry).X = 100\n\n\t// ...\n\n\treturn world\n}\n```\n\nWhat makes systems interesting is that **each works on a subset of entities with specific components**. A single system handles some particular logic relevant only to some entities.\n\nFor example, let’s say we want the color on our tiles to change continuously. So we add a system that iterates over all entities with the Color component and updates the `Color` value.\n\nThe key here is that, **as far as the systems are aware, there’s no such thing as a *tile*.** There are just entities with components on them. Often, systems are generic and work on a small number of components, without broader context of the entire game. This is unusual at first, but it gives you some interesting ways to design the game.\n\n### Drawing the tiles\n\nThe first system we’ll add is the rendering system. It takes entities with `Color` and `Position` components and draws them on the screen. In this example, the tile size is constant, so that’s all the data we need from each entity.\n\nTo see where we’re heading, here’s the game with a debug inspector enabled. Hover over or tap a tile to see its data.\n\n[Open in a new tab](https://threedotslabs.github.io/go-ecs-games/tiles/main.html?inspect=1)\n\nLet’s implement the rendering system. Systems fetch entities with Donburi queries. A query defines which components an entity must have and lets you iterate over the matches.\n\n```\nimport (\n\t\"github.com/yohamta/donburi\"\n\t\"github.com/yohamta/donburi/filter\"\n)\n\nquery := donburi.NewQuery(\n\tfilter.Contains(Position, Color),\n)\n\n// Get all entities with both Position AND Color\nfor entry := range query.Iter(world) {\n\t// Do something with entry\n}\n\n// A different way to do the same thing\nquery.Each(world, func(entry *donburi.Entry) {\n\t// ...\n})\n```\n\nWe create the query in the constructor and keep it as a field of the system struct, to avoid needless allocations every tick. The heavy lifting happens in `Update` or `Draw`.\n\nHere’s the rendering code for our tiles.\n\n```\ntype RenderingSystem struct {\n\tquery     *donburi.Query\n\ttileImage *ebiten.Image\n}\n\nfunc NewRenderingSystem() *RenderingSystem {\n\ttileImage := ebiten.NewImage(TileSize, TileSize)\n\ttileImage.Fill(color.White)\n\n\treturn &RenderingSystem{\n\t\tquery: donburi.NewQuery(\n\t\t\tfilter.Contains(Position, Color),\n\t\t),\n\t\ttileImage: tileImage,\n\t}\n}\n\nfunc (r *RenderingSystem) Draw(w donburi.World, screen *ebiten.Image) {\n\tfor entry := range r.query.Iter(w) {\n\t\tpos := Position.Get(entry)\n\t\tc := Color.Get(entry)\n\n\t\top := &ebiten.DrawImageOptions{}\n\t\top.GeoM.Translate(pos.X, pos.Y)\n\n\t\top.ColorScale.ScaleWithColor(c.Color)\n\n\t\tscreen.DrawImage(r.tileImage, op)\n\t}\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/systems.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L37)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L37)\n\nEvery frame, for each entity with a `Position` and a `Color`, the rendering system tints the white tile image with the entity’s color\nand draws it on the screen at the entity’s position.\n\nNow we only need to create tiles with the correct positions and random colors while creating the world.\n\n```\nfunc createWorld() donburi.World {\n\tw := donburi.NewWorld()\n\n\tfor x := range ScreenWidth / TileSize {\n\t\tfor y := range ScreenHeight / TileSize {\n\t\t\tnewTile(w, float64(x*TileSize), float64(y*TileSize))\n\t\t}\n\t}\n\n\treturn w\n}\n\nfunc newTile(w donburi.World, x, y float64) {\n\ttile := w.Create(Position, Color)\n\tentry := w.Entry(tile)\n\n\tPosition.SetValue(entry, PositionData{\n\t\tX: x,\n\t\tY: y,\n\t})\n\n\tColor.SetValue(entry, ColorData{\n\t\tColor: tileColors[rand.Intn(len(tileColors))],\n\t})\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/main.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L48)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L48)\n\nThis example is trivial, of course. The rendering system is not that universal if all it can do is draw tiles. We’re moving to a more complex project soon, but first, let’s add two more systems to this example.\n\n### Breaking tiles with a click\n\nTo make the tiles a bit less boring, let’s add a way to *break* them: when you click a tile, it should fall down the screen.\n\nWe’ll add two components:\n\n- `Velocity`, so that the tiles move.\n- `Rotation`, for a bit more dramatic visual effect.\n\n```\ntype VelocityData struct {\n\tX float64\n\tY float64\n\n\tRotation float64\n}\n\nvar Velocity = donburi.NewComponentType[VelocityData]()\n\ntype RotationData struct {\n\tAngle float64\n}\n\nvar Rotation = donburi.NewComponentType[RotationData]()\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L16)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L16)\n\nWe’ll add a `VelocitySystem`, making the entities move. It’s a good example of a universal system in action. It updates the position and rotation of entities by the set values. We can forget it exists and set velocity on an entity we need to move.\n\n```\nfunc (v *VelocitySystem) Update(w donburi.World) {\n\tfor entry := range v.query.Iter(w) {\n\t\tpos := Position.Get(entry)\n\t\trot := Rotation.Get(entry)\n\t\tvelocity := Velocity.Get(entry)\n\n\t\tpos.X += velocity.X\n\t\tpos.Y += velocity.Y\n\t\trot.Angle += velocity.Rotation\n\t}\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/systems.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L25)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L25)\n\nNow, we need a system for detecting clicks on the tiles. First, let’s somehow mark the entities that can be clicked, so it’s more explicit. We’ll create a `Clickable` component.\n\nThis component has no data. We use it only to mark that the entity supports clicking on it. For components without data like this, we can use a shortcut from Donburi: a *tag*.\n\n```\nvar Clickable = donburi.NewTag()\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L37)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L37)\n\nWe need to include this tag along with the new components when creating an entity:\n\n```\ntile := w.Create(Position, Rotation, Color, Velocity, Clickable)\n```\n\nThe `ClickSystem` can look like this:\n\n```\nfunc NewClickSystem() *ClickSystem {\n\treturn &ClickSystem{\n\t\tquery: donburi.NewQuery(\n\t\t\tfilter.Contains(Clickable, Velocity),\n\t\t),\n\t}\n}\n\nfunc (c *ClickSystem) Update(w donburi.World) {\n\tp, ok := pressedPoint()\n\tif !ok {\n\t\treturn\n\t}\n\n\tfor entry := range c.query.Iter(w) {\n\t\tpos := Position.Get(entry)\n\n\t\tif p.X >= pos.X && p.X <= pos.X+TileSize &&\n\t\t\tp.Y >= pos.Y && p.Y <= pos.Y+TileSize {\n\n\t\t\tvelocity := Velocity.Get(entry)\n\t\t\tvelocity.X = randomRange(-1, 1)\n\t\t\tvelocity.Y = randomRange(1.5, 2.5)\n\t\t\tvelocity.Rotation = randomRange(-0.1, 0.1)\n\n\t\t\tentry.RemoveComponent(Clickable)\n\t\t}\n\t}\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/tiles/systems.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L80)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L80)\n\nSo once a mouse button is clicked (or the screen is tapped), we iterate over all clickable entities and check if they intersect with the pressed point. If so, we set a random velocity and rotation for the tile. That’s enough to get it moving, since the velocity system picks it up from there.\n\nFinally, we remove the `Clickable` component, so that it’s not possible to click a falling tile again.\n\nSee the end result below:\n\n[Open in a new tab](https://threedotslabs.github.io/go-ecs-games/tiles/main.html)\n\nI also updated the rendering system to take rotation into account. You can see the full source on [GitHub](https://github.com/ThreeDotsLabs/go-ecs-games/tree/main/tiles).\n\nHopefully you got a general idea of how Donburi works so far, but such a simple project doesn’t show the benefits of ECS well. Let’s look at another project.\n\n## A slightly more complete game\n\nWe’ll simulate an aquarium, with the player controlling a friendly pufferfish. It grows by collecting bubbles and needs to avoid other fish around it. The player scores points for the bubbles and loses points by eliminating the poor fish.\n\nTry it yourself (control the pufferfish with WASD; no mobile controls, sorry!).\n\n[Open in a new tab](https://threedotslabs.github.io/go-ecs-games/pufferfish/main.html)\n\nAssets by [Kenney](https://kenney.nl), my usual source of inspiration.\n\nI won’t describe the entire game step by step, but will mention new patterns I introduced there. The full source is on [GitHub](https://github.com/ThreeDotsLabs/go-ecs-games/tree/main/pufferfish).\n\n### Project structure\n\nFor a game this size, it makes sense to split it into packages. One level of packages should be enough.\n\n```\n├── archetype/\n│   └── ...\n├── assets/\n│   └── ...\n├── component/\n│   └── ...\n├── domain/\n│   └── ...\n├── engine/\n│   └── ...\n├── event/\n│   └── events.go\n├── game/\n│   └── game.go\n├── system/\n│   └── ...\n└── main.go\n```\n\n`game` is the entry point, including the `Game` struct and the initial Donburi world.\n\n`component` and `system` packages keep components and systems as described so far.\n\nI like to keep the names singular, so later I get self-explanatory `component.Velocity` and `system.Rendering` types.\n\n`assets` keeps the assets loaded with `go:embed` for easier distribution. It’s a trivial one in this case, just loading all of them on import. For bigger games, it makes sense to add an asynchronous loader here.\n\nIn the `engine` package, I keep common helper functions that don’t belong anywhere. Things like `Timer{}`, `RandomDuration()`, `Rect{}`, etc. Because they are universal (never specific to the game), it’s easy to copy-paste this package when starting a new game and use them right away.\n\nWe’ll get to `archetype`, `domain`, and `event` soon.\n\nThe order of imports goes something like this. A package can’t import anything above it.\n\n![Package import order from top to bottom: game, system, event and archetype, component, domain, engine and assets](https://threedots.tech/post/making-games-in-go-ecs/images/package-imports_hu27d42cac96554d7ba65d38cb7f66876f_78556_857x831_fill_q80_h2_lanczos_smart1_3.webp)\n\n### Position, rotation, and scale\n\nDonburi comes with the `Transform` component, which most entities need. It includes the basic data each object in 2D space has: position, rotation, and scale. We no longer need to define them ourselves, as we did in the tiles example.\n\n```\nimport (\n\t\"github.com/yohamta/donburi/features/math\"\n\t\"github.com/yohamta/donburi/features/transform\"\n)\n\n// ...\n\nentry := w.Entry(w.Create(transform.Transform))\n\nt := transform.GetTransform(entry)\n\nt.LocalPosition = math.Vec2{X: 50, Y: 0}\nt.LocalRotation = 2\nt.LocalScale = math.Vec2{X: 2, Y: 2}\n```\n\nThe 2D vector (`math.Vec2`) also comes from Donburi, and it’s just a pair of (X, Y) values. I described working with position, rotation, and scale in detail in [the previous post](https://threedots.tech/post/making-games-in-go/).\n\n### Archetypes: constructors for entities\n\nWorking with components can get verbose, so I use a high-level API to simplify it. I keep it in the `archetype` package.\n\nThe [API](https://github.com/ThreeDotsLabs/go-ecs-games/blob/main/pufferfish/archetype/entry.go) uses the builder pattern. `New()` creates a new entry with the `Transform` component, and `With()` adds more components.\n\nIn practice, it looks like this:\n\n```\ncam := archetype.New(world).\n\tWith(component.Camera).\n\tWith(component.PositionLimit).\n\tEntry()\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L84)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L84)\n\nFor common objects that can be created in a few places, I also create constructors in the `archetype` package:\n\n```\nfunc NewFish(w donburi.World, pos math.Vec2) *donburi.Entry {\n\tkind := engine.RandomFrom(fishKinds)\n\tscale := engine.RandomFloatRange(domain.FishMinScale, domain.FishMaxScale)\n\n\tfish := New(w).\n\t\tWithPosition(pos).\n\t\tWithSprite(component.SpriteData{\n\t\t\tImage: kind.Sprite,\n\t\t\tLayer: component.LayerBackground,\n\t\t}).\n\t\tWithScale(math.Vec2{\n\t\t\tX: scale,\n\t\t\tY: scale,\n\t\t}).\n\t\tWith(component.Velocity).\n\t\tWith(component.Drag).\n\t\tWith(component.PositionLimit).\n\t\tWith(component.Killable).\n\t\tWith(kind.AI).\n\t\tWith(component.Remains).\n\t\tWithSpriteBounds().\n\t\tEntry()\n\n\tcomponent.Remains.SetValue(fish, component.RemainsData{\n\t\tImage: kind.Skeleton,\n\t})\n\n\t// ...\n\n\treturn fish\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/archetype/fish.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/fish.go#L26)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/fish.go#L26)\n\nNow, creating a new fish is as simple as:\n\n```\nfish := archetype.NewFish(w, math.Vec2{X: 50, Y: 100})\n```\n\nFor some common components like `Sprite`, I extend the builder so the API is even easier to use. For example, the `WithTimeToLive` method adds the `TimeToLive` component and sets its timer to the given duration. It’s easy to extend the API, thanks to keeping it part of the game instead of a generic library.\n\n### Parents and children\n\nTransform supports parent-child relationships, which is super handy. When you make an entity a child of another entity, it’s easy to calculate its position, rotation, and scale, taking entities in the hierarchy into account. In other words, you can make it “follow” the parent.\n\nThe `transform` package exposes an API for this:\n\n```\ntransform.AppendChild(parent, child, false)\ntransform.SetParent(child, parent, false)\n\nparent, ok := transform.GetParent(child)\nchildren, ok := transform.GetChildren(parent)\n```\n\nHave you noticed that `Transform` uses `LocalPosition`, `LocalRotation`, and `LocalScale`? If the entity has no parent, its *local* position is the same as its *world* position. But once it has one, the local position is the position relative to the parent. That’s what the `false` argument to `AppendChild` and `SetParent` controls: with `true`, Donburi recalculates the local position so the child doesn’t move in the world.\n\n![A parent at local and world position (10, 5) and its child at local position (5, 7) and world position (15, 12)](https://threedots.tech/post/making-games-in-go-ecs/images/local-world-position_hu9dfb7f2c4327b25a58b5313d4f986107_61688_861x615_fill_q80_h2_lanczos_smart1_3.webp)\n\nTo read the world values, the `transform` package has functions that return the *world* position, rotation, and scale. “World” in this context means “Local value plus parent and all grandparents”.\n\n```\npos := transform.WorldPosition(child)\nrotation := transform.WorldRotation(child)\nscale := transform.WorldScale(child)\n```\n\nIn practice, this means every time we attach an entity as a child to another entity, we only need to worry about setting its local position. All systems using the world position will treat it as being *attached* to the parent.\n\nWe use parent-child relationships when spawning a new bubble. We have a couple of *spawner* entities in the game world. They are invisible and create new bubbles around them.\n\nWhen a new bubble appears on a timer, we set its local position:\n\n```\npos := math.Vec2{\n\tX: engine.RandomFloatRange(-200, 200),\n\tY: engine.RandomFloatRange(-200, 200),\n}\n\nbubble := New(w).\n\tWithParent(parent).\n\tWithPosition(pos).\n\t// ...\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/archetype/bubble.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/bubble.go#L41)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/bubble.go#L41)\n\nBecause the spawner is set as the parent, we can just get a random distance between -200 and 200, and the bubble will appear within that distance of the spawn point. If we move the spawners, the bubbles will follow them.\n\n### Layers and the camera\n\nThe rendering system is more universal now. The key element is the `Sprite` component, representing an image we draw:\n\n```\ntype Layer int\n\nconst (\n\tLayerBackground Layer = iota\n\tLayerPlayer\n\tLayerForeground\n)\n\ntype SpriteData struct {\n\tImage *ebiten.Image\n\tLayer Layer\n\tFlipX bool\n}\n\nfunc (s SpriteData) Order() int {\n\t// Used by ordered query\n\treturn int(s.Layer)\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/sprite.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/sprite.go#L8)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/sprite.go#L8)\n\nWe support layers. The lower layers get drawn first on the screen, so higher layers end up on top. The `Order()` method makes sprites work with Donburi’s ordered queries, which iterate over entities sorted by layer.\n\nLayers are just arbitrary numbers, but we define a few constants. We’ll have all fish in the background, the player on top of them, and the bubbles above everything else.\n\n![Three overlapping layers: Background at the bottom, Player in the middle, and Foreground on top](https://threedots.tech/post/making-games-in-go-ecs/images/layers_hu9ea9391b98069f33c884d4c10d20f1af_47706_986x662_fill_q80_h2_lanczos_smart1_3.webp)\n\nWe use a single *camera* that follows the player. We draw the entire game world on the `offscreen` image in memory. Then, we paint a portion of it onto the actual screen, offset by the camera position.\n\n![The camera rectangle around the player inside a larger game world, offset by X and Y from the world's origin](https://threedots.tech/post/making-games-in-go-ecs/images/camera_hu14e4b124f2a751995df0dcab070fec3b_82230_986x662_fill_q80_h2_lanczos_smart1_3.webp)\n\n```\ncam, ok := r.cameraQuery.First(w)\nif !ok {\n\treturn\n}\ncamPos := transform.WorldPosition(cam)\n\nop := &ebiten.DrawImageOptions{}\nop.GeoM.Translate(-camPos.X, -camPos.Y)\nscreen.DrawImage(r.offscreen, op)\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/rendering.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/rendering.go#L67)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/rendering.go#L67)\n\n### Rendering text\n\nRendering text is similar to rendering sprites, but simpler. We use a new component:\n\n```\ntype TextData struct {\n\tText string\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/text.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/text.go#L7)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/text.go#L7)\n\nWe draw entities with this component the same way we draw sprites, but with text instead. This could be improved by extending the component data with things like text color, font size, alignment, etc.\n\nBecause of the order of *drawers*, text will always appear on top of the sprites. For our use case, that’s good enough.\n\n```\ng.drawers = []Drawer{\n\tsystem.NewRendering(),\n\tsystem.NewTextRendering(),\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L56)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L56)\n\n### Composition in practice\n\nHere’s a comparison of some of the entities and components we use:\n\n![Components of the Player, Fish, Bubble, and Camera entities: all have Transform, the player adds Input, Player, and Killer, the fish add Killable, Remains, and one of four AI components, bubbles add Collectable and Time To Live, and the camera adds Camera](https://threedots.tech/post/making-games-in-go-ecs/images/entity-components_huf8fc35784e20d320a26116b35fb9ac03_280931_1972x1508_fill_q80_h2_lanczos_smart1_3.webp)\n\nTip\n\nComponents aren’t just buckets for data, but they should give you a clear idea of what can happen with the entity. Try to find names that clearly describe what the component represents.\n\n### Movement and controls\n\nWe use a similar `Velocity` system to the one in the previous example.\n\nI wanted to make controls feel a bit like swimming, so there’s also the `Drag` system. It reduces the velocity of entities with the `Drag` component over time. This way, after you press a movement button, the player moves for a bit and gradually stops.\n\nDrag also works on other fish, but not on bubbles, which have constant upward velocity. This is an example of how you can control which entities a system handles, and which it doesn’t. `Drag` is a tag, so it enables or disables the behavior for the chosen entities. We could also dynamically add or remove it.\n\n### Keeping entities within world boundaries\n\nWe use the same mechanism to limit the camera, player, and fish positions, so they never leave the world edges.\n\n```\ncomponent.PositionLimit.SetValue(player, component.PositionLimitData{\n\tMin: math.Vec2{},\n\tMax: math.Vec2{X: domain.MapWidth, Y: domain.MapHeight},\n})\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/archetype/player.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/player.go#L36)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/player.go#L36)\n\nFor the camera, we adjust the limit based on the screen dimensions:\n\n```\ncomponent.PositionLimit.SetValue(cam, component.PositionLimitData{\n\tMin: math.Vec2{X: 0, Y: 0},\n\tMax: math.Vec2{X: domain.MapWidth - ScreenWidth, Y: domain.MapHeight - ScreenHeight},\n})\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L93)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L93)\n\nNote how the limit system works the same for entities as different as the camera and the player, with a slight adjustment of the boundaries.\nWe don’t add the `PositionLimit` component to the bubbles, because they can *escape* upwards.\n\n### Fish behaviors\n\nI thought it would be fun to give each fish color a different behavior, like ghosts in Pac-Man:\n\n- Blue fish are idle, moving up and down and left and right just a bit.\n- Orange fish choose a cardinal direction and swim for a bit.\n- Red fish chase the player, then step away once they get close.\n- Green fish slowly swim towards the player, then quickly flee once they get close.\n\nEach type needs a different state (timers and other data). Instead of using a single component, I decided to go with four, one for each AI type. But there’s still one system. I used a query that combines any of the components:\n\n```\nquery: donburi.NewQuery(\n\tfilter.Or(\n\t\tfilter.Contains(component.IdleAI),\n\t\tfilter.Contains(component.RandomMovementAI),\n\t\tfilter.Contains(component.ChasePlayerAI),\n\t\tfilter.Contains(component.FleePlayerAI),\n\t),\n),\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/ai.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L29)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L29)\n\nThen, I branch out:\n\n```\nfor entry := range a.query.Iter(w) {\n\tif entry.HasComponent(component.IdleAI) {\n\t\ta.handleIdleAI(entry)\n\t} else if entry.HasComponent(component.RandomMovementAI) {\n\t\ta.handleRandomMovementAI(entry)\n\t} else if entry.HasComponent(component.ChasePlayerAI) {\n\t\ta.handleChasePlayerAI(w, entry)\n\t} else if entry.HasComponent(component.FleePlayerAI) {\n\t\ta.handleFleePlayerAI(w, entry)\n\t} else {\n\t\tpanic(\"entity has AI component but no known AI type\")\n\t}\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/ai.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L43)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L43)\n\nFour systems would work just as well. I chose a bit less boilerplate.\n\n### Bounds smaller than the sprite\n\n`Bounds` is a component that represents the entity’s boundaries in the game world. For example, we use it to check collisions. It’s the entity’s 2D dimensions.\n\n```\ntype BoundsData struct {\n\tWidth  float64\n\tHeight float64\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/bounds.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L9)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L9)\n\nThe simplest way is to use the image size as bounds. But we create a separate component to have more control over the dimensions.\n\nWe make the bounds a bit smaller than the image. This reduces the collision area. Otherwise, the player would collide with the fish by touching the transparent parts, which would be unintuitive and annoying.\n\n![A fish and the pufferfish with dashed rectangles marking their bounds, smaller than the sprites, with the width and height labeled](https://threedots.tech/post/making-games-in-go-ecs/images/bounds_hu60ce5414acd4c87089abebda42cad176_59867_795x560_fill_q80_h2_lanczos_smart1_3.webp)\n\nWe create a `Rect()` method that returns a struct filled with the entity’s position together with the bounds, taking *scale* into account.\n\n```\nfunc (d BoundsData) Rect(e *donburi.Entry) engine.Rect {\n\tscale := transform.WorldScale(e)\n\tpos := transform.WorldPosition(e)\n\tw := d.Width * scale.X\n\th := d.Height * scale.Y\n\treturn engine.NewRect(pos.X-w/2, pos.Y-h/2, w, h)\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/bounds.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L15)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L15)\n\nTaking scale into account matters because we’ll use different scales for the fish, and the player’s scale will change during gameplay. All logic related to the boundaries needs to consider this.\n\nCalling this method is a bit unusual because of how components work. The `BoundsData` struct keeps only the dimensions, so we also need to pass the entry to `Rect` to get the current position.\n\n```\nbounds := component.Bounds.Get(entry)\nrect := bounds.Rect(entry)\n\nif rect.Intersects(anotherRect) {\n\t// ...\n}\n```\n\nThere’s a trivial `Debug` system that flips a boolean debug flag. When the flag is on, the rendering system draws the bounds around the sprites.\n\n![The aquarium game with rectangles drawn around every fish and bubble](https://threedots.tech/post/making-games-in-go-ecs/images/debug-bounds_hub326aff574b5aa73059843be409c5849_324088_2112x1682_fill_q80_h2_lanczos_smart1_3.webp)\n\nAn easy way to visually debug the boundaries.\n\n### Decoupling systems with events\n\nDonburi supports [events](https://academy.threedots.tech/knowledge/event/). It’s a simple mechanism, as we still have one game loop running. We don’t do any asynchronous processing.\n\nInstead, we *publish* events in memory and process them each tick, which means we call all functions that have *subscribed* to them.\n\nI like working with events because they let you [decouple concepts](https://academy.threedots.tech/knowledge/event-driven-architecture/) in the game. Many game elements are connected, and over time the logic becomes full of calls to different parts, which is hard to follow.\n\nLet’s consider the `Kill` system from our game. We look for intersections between a killer (the player object) and a killable (other fish). Once they intersect, we destroy the fish and reduce the player’s points.\n\n```\nfunc (k *Kill) Update(w donburi.World) {\n\tfor killerEntry := range k.killerQuery.Iter(w) {\n\t\tfor killableEntry := range k.killableQuery.Iter(w) {\n\t\t\tkillerBounds := component.Bounds.Get(killerEntry)\n\t\t\tkillableBounds := component.Bounds.Get(killableEntry)\n\n\t\t\tif killerBounds.Rect(killerEntry).Intersects(killableBounds.Rect(killableEntry)) {\n\t\t\t\tcomponent.Destroy(killableEntry)\n\n\t\t\t\t// TODO Take points out of player's score\n\t\t\t}\n\t\t}\n\t}\n}\n```\n\nThe thing is, adding scoring logic here feels beyond the responsibility of this system. It would work just fine, but note how *generic* the system is now. It doesn’t know anything about fish or the player. It just makes sure that a killer destroys a killable it intersects with.\n\nSo we define a `Killed` event in the `event` package:\n\n```\nimport \"github.com/yohamta/donburi/features/events\"\n\ntype KilledData struct {\n\tPoints int\n}\n\nvar Killed = events.NewEventType[KilledData]()\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/event/events.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/event/events.go#L13)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/event/events.go#L13)\n\nAnd publish it in the `Kill` system:\n\n```\nif killerBounds.Rect(killerEntry).Intersects(killableBounds.Rect(killableEntry)) {\n\tcomponent.Destroy(killableEntry)\n\n\tevent.Killed.Publish(w, event.KilledData{\n\t\tPoints: component.Killable.Get(killableEntry).Points,\n\t})\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/kill.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/kill.go#L35)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/kill.go#L35)\n\nWe define event handlers on systems, since that is where most of the game’s logic lives. The `Scoring` system subscribes to the `Killed` and `Collected` events.\n\n```\nfunc (s *Scoring) Subscribe(w donburi.World) {\n\tevent.Killed.Subscribe(w, s.onKilled)\n\tevent.Collected.Subscribe(w, s.onCollected)\n}\n\nfunc (s *Scoring) onKilled(w donburi.World, e event.KilledData) {\n\ts.updateScore(w, e.Points)\n}\n\nfunc (s *Scoring) onCollected(w donburi.World, e event.CollectedData) {\n\ts.updateScore(w, e.Points)\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/scoring.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/scoring.go#L25)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/scoring.go#L25)\n\nWe call `Subscribe` once, right after creating the world. We process the events in the main `Update` method. Note that events also live in Donburi’s world.\n\n```\n func (g *Game) Update() error {\n \tfor _, s := range g.systems {\n \t\ts.Update(g.world)\n \t}\n\n+\tevents.ProcessAllEvents(g.world)\n\n \treturn nil\n }\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L122)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L122)\n\n### Deferred `Destroy`\n\nTo remove an entity from the world, you can call `entry.Remove()`. But another system down the stack might still have a leftover reference to it, and then your game will crash. You can check if the entity is valid with `entry.Valid()`, but it adds a lot of noise to the logic code.\n\nI kept running into this issue over and over, and finally changed the approach.\n\nInstead of removing the entities, we mark them as *destroyed* with a tag. We can use a helper method:\n\n```\nvar Destroyed = donburi.NewTag()\n\nfunc Destroy(e *donburi.Entry) {\n\tif !e.Valid() {\n\t\treturn\n\t}\n\tif !e.HasComponent(Destroyed) {\n\t\te.AddComponent(Destroyed)\n\t}\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/destroyed.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/destroyed.go#L7)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/destroyed.go#L7)\n\nThe `Destroy` system cleans up the destroyed entities, like a garbage collector. `RemoveRecursive` also removes all children in the hierarchy.\n\n```\nfunc (d *Destroy) Update(w donburi.World) {\n\tfor entry := range d.query.Iter(w) {\n\t\ttransform.RemoveRecursive(entry)\n\t}\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/destroy.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/destroy.go#L22)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/destroy.go#L22)\n\nThe order of systems usually doesn’t matter, but here it’s important. `Destroy` is the last system in the stack, to give other systems a chance to process the entity before it’s removed for good.\nNote the `Remains` system, which leaves a skeleton where a fish died. It queries destroyed entities and needs to run before they are removed for good.\n\n```\n g.systems = []System{\n \t// ...\n \tsystem.NewKill(),\n \tsystem.NewTimeToLive(),\n \tsystem.NewRemains(),\n+\tsystem.NewDestroy(),\n }\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L41)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L41)\n\n### Game rules in the domain package\n\nFor a while, I looked for a good place to keep some of the game’s constants, like the movement speed, initial health points, etc. When you hardcode these values in systems, updating them is annoying.\n\nSimilarly, there is often some logic inside systems that’s more related to the inherent game rules than how it works in Ebitengine or Donburi. For example, how some effects stack or how damage is calculated.\n\nI keep this kind of code in the `domain` package. I took the name from [DDD](https://academy.threedots.tech/knowledge/ddd/) because it felt the most natural to me. The key is that it’s separate, doesn’t import any other game packages, and it’s easy to change and [test](https://academy.threedots.tech/knowledge/unit-tests/).\n\n```\npackage domain\n\nimport \"time\"\n\nconst (\n\tFishKillPenalty = -10\n\n\tFishMinScale = 0.4\n\tFishMaxScale = 1.2\n\n\tChaseFallBackDistance = 75.0\n\tChaseRange            = 400.0\n\tFleeDistance          = 150.0\n\n\tBubbleTimeToLive  = 60 * time.Second\n\tRemainsTimeToLive = 3 * time.Minute\n)\n\nfunc FishSpeed(base float64, scale float64) float64 {\n\treturn base / scale\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/domain/fish.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/domain/fish.go#L5)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/domain/fish.go#L5)\n\nFor example, we use the domain rule that “big fish swim slower” in a few spots in the fish AI system. If we wanted to change how it’s calculated, or what else it depends on, we’d change it in one place.\n\n```\nspeed := domain.FishSpeed(engine.RandomFloatRange(0.7, 1.2), t.LocalScale.X)\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/ai.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L159)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L159)\n\nThe `domain` package is a great place for all kinds of testing, since it’s [pure logic](https://academy.threedots.tech/knowledge/domain-layer/) and doesn’t need the rest of the game engine to work.\n\nYou could also build a way to change the domain constants live during gameplay for easier playtesting. Choosing these values is often key to making the game fun to play.\n\n### Singletons as entities\n\nSometimes, you need a single copy of an object to track data. For example, I keep the screen size and debug toggle in the `Settings` component. There’s always a single instance of it in the world, and I use a dedicated `MustFindSettings()` function to get it.\n\n```\ntype SettingsData struct {\n\tScreenWidth  int\n\tScreenHeight int\n\n\tDebug bool\n}\n\nvar Settings = donburi.NewComponentType[SettingsData]()\n\nvar settingsQuery = donburi.NewQuery(filter.Contains(Settings))\n\nfunc MustFindSettings(w donburi.World) *SettingsData {\n\tentry, ok := settingsQuery.First(w)\n\tif !ok {\n\t\tpanic(\"settings not found\")\n\t}\n\n\treturn Settings.Get(entry)\n}\n```\n\nFull source: [github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/settings.go](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/settings.go#L8)\n\n[Full source](https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/settings.go#L8)\n\nAn alternative would be to use a global variable. But I like to stick to the ECS primitives because the `world` is already passed everywhere, and it’s easy to query what you need from it.\n\nWe could also cache these singletons inside systems instead of fetching them every tick. The problems start once you do something unusual, like restarting the level, loading a game, or testing with multiple world instances. I prefer to keep the systems completely stateless, so that the `world` you pass to `Update()` keeps the entire game state.\n\nDon’t overuse singletons. We have a single camera and player instance now, but it could take the game in an interesting direction if we added more. **ECS works best when you don’t treat the entities as unique snowflakes.**\n\n## When ECS shines\n\nHere’s an example of how the game can change with a few lines of code. Controlling the player works thanks to the `Input` component. Try adding it to the fish on collision, instead of destroying them:\n\n```\n-component.Destroy(killableEntry)\n+killableEntry.AddComponent(component.Input)\n+// Copy the component data over from the player\n+component.Input.SetValue(killableEntry, component.Input.GetValue(killerEntry))\n```\n\nThe fish now start following the player’s moves. But they keep their AI, too, so we need to keep moving to keep them close. Maybe that’s an interesting mechanic? I didn’t plan it beforehand, but I came across it while experimenting with the components. **Note we didn’t have to touch the systems at all, because they are generic enough to work with many component configurations.**\n\n## When ECS is too much\n\nAs much as I like working with ECS, it’s not a silver bullet.\nIt works great in games that simulate many objects with similar behaviors, as we’ve seen so far.\n\nBut for many projects, it can feel like too much boilerplate and code scattered with no benefit.\n\nYou can’t open the entity’s code and read through its logic, because it’s spread across systems.\n\nIt can be difficult to track bugs that happen when systems interact with each other. Not all logic can be captured as an elegant, standalone `Update` function.\n\nI sometimes choose a hybrid approach for entities that are an exception.\nA simple `Script` component with a custom `Update` function can work fine. I’ll just code the custom logic for the specific entity instead of forcing multiple systems to make it work.\n\n```\ntype ScriptData struct {\n\tUpdate func(entry *donburi.Entry)\n}\n```\n\nYou can also run custom logic in Ebitengine’s `Update()` and `Draw()` methods next to the systems. Donburi is easy to plug in where you need it, so you don’t need to go all in. For example, you could keep the game’s UI out of it.\n\n## Evolving your engine\n\nWhat I described above isn’t an up-front design I made up, but what I ended up with after making games with this architecture and tweaking the approach as I went. Don’t treat it as a definitive guide, but rather as a starting point, and take it from here.\n\nI like how polishing the approach made the next games easier. (Obviously, starting projects is way more fun than finishing them. 😅) It freed me from the constant “how to model this?” questions. Instead, I have some familiar ground to start with.\n\nSpecifically, it’s easy to copy components and systems between games. Many, like rendering, are universal and can be slightly adjusted, so you never start from zero.\n\n## Making games with AI agents\n\nI’m experimenting a lot these days. I also tried making games with agents while keeping the architecture I’m used to. It’s a lot of fun to describe what you have in mind and have quite a polished version in front of you in minutes.\n\nBut working this way makes you less involved in the project. As the game gets more complex, you no longer have a clear idea of how everything ties together. That may also be true with old-school typing, but I feel it happens sooner when using AI.\n\nAnother downside is that it’s much more tempting to create new features (because it’s so quick) than to polish existing ones and playtest the game so it’s fun to play. Not a big deal if you’re just having fun. But I think there’s value in going through the whole process yourself, although I can’t yet name it precisely.\n\nGamedev can get ridiculously complex, but many parts work the same way across games. To keep the games built by agents in a familiar structure, I boiled down the approach from my earlier Ebitengine and Donburi games into *patterns*: Markdown files that agents can follow.\n\nA couple of thoughts before you see the patterns:\n\n- These are regular Markdown files, not some specialized *skills*. I don’t think any more structure is needed: recent models are smart enough to pick them up with a one-line hint.\n- They are not some secret spells that will make a great game. **They worked well for me because I already know the architecture and I feel good working in it.**\n- I did not review all of them. They’re not supposed to work as linters, but to give LLMs a general direction that I can verify if needed.\n- I coded the Tiles and Pufferfish games by hand (with pleasure!), so I didn’t use the patterns for them. They follow the same ideas, though.\n\nYou’ll find the files [in the patterns directory](https://github.com/ThreeDotsLabs/go-ecs-games/tree/main/patterns).\n\n## More examples\n\nYou can find the full source for both games [on GitHub](https://github.com/ThreeDotsLabs/go-ecs-games).\n\nIf you want to see the code for bigger projects, here are some (unfinished 🥴) games I built with the same approach:\n\n- [A Night in Innsmouth](https://github.com/m110/a-night-in-innsmouth), a narrative game based on the prose of H. P. Lovecraft.\n- [Kingdoms](https://github.com/m110/kingdoms), a strategy game with terrain generation.\n- [Witchcraft](https://github.com/m110/witchcraft), a local battle arena with different classes and spells.\n\nThanks for reading and have fun making your own games! If you found it useful or would like to read more about some topic, let me know in the comments.\n","body_html":"<p>Even if you use AI, it’s still worth learning the foundations. I found it easier to steer agents when they work on a project where I had already put the scaffolding in place. They’re much better at imitation than coming up with something new. (I share the patterns I give agents <a href=\"#making-games-with-ai-agents\">at the end</a>.)</p>\n<p><strong>Learning software concepts isn’t only about the code. It also changes how you think about projects.</strong> You know what systems are in place, how the elements interact, and what a good solution would be. I care more than ever about keeping my mental models sharp now that AI can produce infinite output that’s worthless unless someone decides otherwise.</p>\n<p>Note</p>\n<p>The usual disclaimer: I’m a hobbyist making <a href=\"https://github.com/m110/\" rel=\"nofollow ugc noopener\">tiny 2D games</a>. I do it for fun, and have never shipped a professional game. I write about what has worked for me, and it could be something dumb. (If that’s the case, let me know in the comments!)</p>\n<h2 id=\"why-bother-with-ecs\">Why bother with ECS?</h2>\n<p><a href=\"https://threedots.tech/post/making-games-in-go/\" rel=\"nofollow ugc noopener\">Previously</a>, I described a simple approach to working with game objects. Each object is a struct and has its own <code>Update()</code> and <code>Draw()</code> methods. In the game loop, we iterate over all the objects and call their methods.</p>\n<pre><code>type Player struct {\n    Position Vector\n    Sprite   *ebiten.Image\n}\n\nfunc NewPlayer() *Player {\n    return &amp;Player{\n        Position: Vector{\n            X: 100,\n            Y: 100,\n        },\n        Sprite:   PlayerSprite,\n    }\n}\n\nfunc (p *Player) Update() {\n    p.Position.X += 10\n}\n\nfunc (p *Player) Draw(screen *ebiten.Image) {\n    op := &amp;ebiten.DrawImageOptions{}\n    op.GeoM.Translate(p.Position.X, p.Position.Y)\n    screen.DrawImage(p.Sprite, op)\n}</code></pre>\n<p>This is a good start. It’s easy to follow how the game works and to add new objects. But as the game becomes more complex, it gets messy. The <code>Update</code> methods get long. You need to pass many references around, because objects don’t know about other objects. Some logic doesn’t clearly belong to any one object.</p>\n<p>Another challenge in many games is that objects have similar traits, but aren’t quite the same thing. For example, a player character, an NPC, and an enemy are very similar objects, but also completely different gameplay-wise. They all have health points, move in the game world, collide with the terrain, and so on. But one is controlled by the player, one you can talk to to accept a quest, and one attacks you on sight.</p>\n<p>One way to approach this is with some kind of inheritance (or embedding in Go). You create a basic <code>Object</code> with all common traits, then extend it with more specific entities.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/inheritance_hubc71d098305ed46df1b16520ffa98065_56195_697x562_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"A base Entity type with Player, NPC, and Enemy types built on top of it\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>But what if you want an NPC to turn hostile after an interaction? Or if you want the player to sometimes talk to the enemy? Or if you want to briefly take control over any of them? The inheritance model stops working, and you need workarounds that can get ugly.</p>\n<p>I’ve been trying to figure this out, and I discovered the Entity Component System (ECS) architecture. It became my go-to approach for making games. I’m using the <a href=\"https://github.com/yohamta0/donburi-ecs\" rel=\"nofollow ugc noopener\">Donburi</a> ECS library in Go together with the <a href=\"https://ebitengine.org\" rel=\"nofollow ugc noopener\">Ebitengine</a> 2D game engine. Both are super fun to work with.</p>\n<p>You may see ECS mentioned for performance reasons (storing components of one type together in memory makes iterating over them fast), but for me, <strong>the best part is the mental model shift</strong>. You split the game into small building blocks with clear responsibilities, so it’s easier to think about how it works. Keeping the data separate from the behavior is also an interesting idea that can help you approach other software projects.</p>\n<h2 id=\"entities-components-and-systems\">Entities, components, and systems</h2>\n<p>Note</p>\n<p>If you want to follow along, I recommend reading <a href=\"https://threedots.tech/post/making-games-in-go/\" rel=\"nofollow ugc noopener\">the previous post</a> first, where I explain the basics of Ebitengine.</p>\n<p>In ECS, you split your game into three parts:</p>\n<ul><li><strong>Entities:</strong> generic “objects” that appear in your game. They have no behavior on their own, no dedicated structs, and no <code>Update</code> or <code>Draw</code> methods. An entity on its own is essentially an ID. It’s a unique thing that exists in the game.</li><li><strong>Components:</strong> plain data structs that you’ll attach to the entities. They describe whatever attributes the entity has. For example: position, health points, velocity, etc. They’re like building blocks that make up each entity.</li><li><strong>Systems:</strong> the actual game logic. <code>Update</code> loops that do something with the entities with specific components on them.</li></ul>\n<p>It’s like an extreme take on the Single Responsibility Principle. You clearly separate identity, data, and behavior in the code.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/objects-vs-ecs_hu0548950b3e9d82c5977c95875605d4b6_334498_1988x1226_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"Plain game objects, each with its own Render and Update, compared to ECS entities made of components and processed by separate systems\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>Let’s consider a trivial example to see how it works. We’ll display a grid of colorful tiles on the screen.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/tiles_hu32d8dd9b5124023c269320e0f62f673a_571384_2272x2208_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"A grid of colorful square tiles\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>Each tile is an entity. An entity has no attributes by itself. Our game has 240 tiles. To give them meaning, we need to add components to them.</p>\n<p>Let’s think of a minimal set of components the entity needs to appear as a tile on the screen.</p>\n<p>Without a doubt, it needs a position in the game world, a pair of <code>X</code> and <code>Y</code> coordinates:</p>\n<pre><code>type PositionData struct {\n    X float64\n    Y float64\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L9\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L9\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>The other thing is the tile’s color. That’s a separate component:</p>\n<pre><code>type ColorData struct {\n    Color color.Color\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L22\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L22\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Now, it would be natural to represent the tile like this:</p>\n<pre><code>type Tile struct {\n    Position PositionData\n    Color    ColorData\n}</code></pre>\n<p>But <strong>this isn’t what we want.</strong> As strange as it sounds, our game shouldn’t have a <code>Tile</code> struct. In ECS, there’s no place for a dedicated <code>Tile</code> type. Instead, we have <em>generic</em> entities made of components.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/tile-components_hu27e00c1b867f93ef1cec5dc19722974c_92402_1772x658_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"A tile entity made of a Position and a Color component\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<h3 id=\"working-with-donburi\">Working with Donburi</h3>\n<p>Let’s start working with Donburi primitives.</p>\n<p>The structs we created above (<code>PositionData</code> and <code>ColorData</code>) hold the components’ <em>data</em>. We need to register component types as well. These are global variables:</p>\n<pre><code>import &quot;github.com/yohamta/donburi&quot;\n\nvar (\n    Position = donburi.NewComponentType[PositionData]()\n    Color    = donburi.NewComponentType[ColorData]()\n)</code></pre>\n<p>To create an entity, we first have to create a <em>world</em>. It’s where Donburi tracks entities. Our game will have a single world with all entities living inside.</p>\n<pre><code>world := donburi.NewWorld()</code></pre>\n<p>We create an entity for the tile with two components:</p>\n<pre><code>entity := world.Create(Position, Color)</code></pre>\n<p>The entity lives inside the world from now on. We don’t need to keep track of it. <code>Create</code> returns an integer, because the entity is just an ID.</p>\n<p>If we want to interact with the entity, we need to get its <em>entry</em> from the world:</p>\n<pre><code>entry := world.Entry(entity)</code></pre>\n<p>The entry is a regular Go pointer, and it lets you do something useful with the entity, like reading or setting its component data.</p>\n<p>At this point, the entity has two components attached: <code>Position</code> and <code>Color</code> (because we passed them to <code>world.Create()</code>). They hold zero values of their data structs.</p>\n<p>We can read their data with the component’s <code>Get</code> method. This may be a bit unusual at first, since we call a method on the global component type, not directly on the entry.</p>\n<pre><code>pos := Position.Get(entry)\ncolor := Color.Get(entry)\n\n// pos.X == 0</code></pre>\n<p>To set a value, we can use <code>SetValue</code> like this:</p>\n<pre><code>Position.SetValue(entry, PositionData{\n    X: 100,\n    Y: -50,\n})</code></pre>\n<p>Or by changing the struct in place, since <code>Get</code> returns a pointer:</p>\n<pre><code>pos := Position.Get(entry)\npos.X += 10</code></pre>\n<p>We can also add or remove components and check if they exist:</p>\n<pre><code>if entry.HasComponent(Color) {\n    entry.RemoveComponent(Color)\n}\n\nentry.AddComponent(Color)</code></pre>\n<h3 id=\"introducing-systems\">Introducing systems</h3>\n<p>The last part we need is systems. They are similar to regular <code>Update</code> functions.</p>\n<p>As a reminder, here’s a minimal Ebitengine game (I’m skipping the <code>Layout</code> method, which isn’t relevant). <code>Update</code> is called every <em>tick</em>, usually 60 times per second, and <code>Draw</code> is called every <em>frame</em>.</p>\n<pre><code>type Game struct {}\n\nfunc (g *Game) Update() error {\n    return nil\n}\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n\n}</code></pre>\n<p>In ECS, we move all the code from <code>Update()</code> and <code>Draw()</code> into systems. While Donburi has an experimental systems feature, I’ll stick to a manual but simpler approach here.</p>\n<p>A <em>system</em> is an <code>Update</code> function that works within a given <code>world</code>.</p>\n<pre><code>type System interface {\n    Update(w donburi.World)\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L24\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/main.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L24\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>We keep the world and a slice of systems in the <code>Game</code> struct. Then, we iterate over the systems in the <code>Update</code> method. Each tick, we update every system in the game.</p>\n<pre><code>type Game struct {\n    world   donburi.World\n    systems []System\n}\n\nfunc (g *Game) Update() error {\n    for _, s := range g.systems {\n        s.Update(g.world)\n    }\n\n    return nil\n}</code></pre>\n<p>We’ll also keep systems for drawing on the screen. I’ll call this kind of a system a <code>Drawer</code>, following the Go convention:</p>\n<pre><code>type Drawer interface {\n    Draw(w donburi.World, screen *ebiten.Image)\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L28\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/main.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L28\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Note that a single system could expose both the <code>Update</code> and <code>Draw</code> methods.</p>\n<p>A complete game could look like this:</p>\n<pre><code>type Game struct {\n    world   donburi.World\n    systems []System\n    drawers []Drawer\n}\n\nfunc NewGame() *Game {\n    return &amp;Game{\n        world: createWorld(),\n        systems: []System{\n            NewClickSystem(),\n            NewVelocitySystem(),\n        },\n        drawers: []Drawer{\n            NewRenderingSystem(),\n        },\n    }\n}\n\nfunc (g *Game) Update() error {\n    for _, s := range g.systems {\n        s.Update(g.world)\n    }\n\n    return nil\n}\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n    for _, d := range g.drawers {\n        d.Draw(g.world, screen)\n    }\n}\n\nfunc createWorld() donburi.World {\n    world := donburi.NewWorld()\n\n    tile := world.Create(Position, Color)\n    tileEntry := world.Entry(tile)\n    Position.Get(tileEntry).X = 100\n\n    // ...\n\n    return world\n}</code></pre>\n<p>What makes systems interesting is that <strong>each works on a subset of entities with specific components</strong>. A single system handles some particular logic relevant only to some entities.</p>\n<p>For example, let’s say we want the color on our tiles to change continuously. So we add a system that iterates over all entities with the Color component and updates the <code>Color</code> value.</p>\n<p>The key here is that, <strong>as far as the systems are aware, there’s no such thing as a <em>tile</em>.</strong> There are just entities with components on them. Often, systems are generic and work on a small number of components, without broader context of the entire game. This is unusual at first, but it gives you some interesting ways to design the game.</p>\n<h3 id=\"drawing-the-tiles\">Drawing the tiles</h3>\n<p>The first system we’ll add is the rendering system. It takes entities with <code>Color</code> and <code>Position</code> components and draws them on the screen. In this example, the tile size is constant, so that’s all the data we need from each entity.</p>\n<p>To see where we’re heading, here’s the game with a debug inspector enabled. Hover over or tap a tile to see its data.</p>\n<p><a href=\"https://threedotslabs.github.io/go-ecs-games/tiles/main.html?inspect=1\" rel=\"nofollow ugc noopener\">Open in a new tab</a></p>\n<p>Let’s implement the rendering system. Systems fetch entities with Donburi queries. A query defines which components an entity must have and lets you iterate over the matches.</p>\n<pre><code>import (\n    &quot;github.com/yohamta/donburi&quot;\n    &quot;github.com/yohamta/donburi/filter&quot;\n)\n\nquery := donburi.NewQuery(\n    filter.Contains(Position, Color),\n)\n\n// Get all entities with both Position AND Color\nfor entry := range query.Iter(world) {\n    // Do something with entry\n}\n\n// A different way to do the same thing\nquery.Each(world, func(entry *donburi.Entry) {\n    // ...\n})</code></pre>\n<p>We create the query in the constructor and keep it as a field of the system struct, to avoid needless allocations every tick. The heavy lifting happens in <code>Update</code> or <code>Draw</code>.</p>\n<p>Here’s the rendering code for our tiles.</p>\n<pre><code>type RenderingSystem struct {\n    query     *donburi.Query\n    tileImage *ebiten.Image\n}\n\nfunc NewRenderingSystem() *RenderingSystem {\n    tileImage := ebiten.NewImage(TileSize, TileSize)\n    tileImage.Fill(color.White)\n\n    return &amp;RenderingSystem{\n        query: donburi.NewQuery(\n            filter.Contains(Position, Color),\n        ),\n        tileImage: tileImage,\n    }\n}\n\nfunc (r *RenderingSystem) Draw(w donburi.World, screen *ebiten.Image) {\n    for entry := range r.query.Iter(w) {\n        pos := Position.Get(entry)\n        c := Color.Get(entry)\n\n        op := &amp;ebiten.DrawImageOptions{}\n        op.GeoM.Translate(pos.X, pos.Y)\n\n        op.ColorScale.ScaleWithColor(c.Color)\n\n        screen.DrawImage(r.tileImage, op)\n    }\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L37\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/systems.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L37\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Every frame, for each entity with a <code>Position</code> and a <code>Color</code>, the rendering system tints the white tile image with the entity’s color\nand draws it on the screen at the entity’s position.</p>\n<p>Now we only need to create tiles with the correct positions and random colors while creating the world.</p>\n<pre><code>func createWorld() donburi.World {\n    w := donburi.NewWorld()\n\n    for x := range ScreenWidth / TileSize {\n        for y := range ScreenHeight / TileSize {\n            newTile(w, float64(x*TileSize), float64(y*TileSize))\n        }\n    }\n\n    return w\n}\n\nfunc newTile(w donburi.World, x, y float64) {\n    tile := w.Create(Position, Color)\n    entry := w.Entry(tile)\n\n    Position.SetValue(entry, PositionData{\n        X: x,\n        Y: y,\n    })\n\n    Color.SetValue(entry, ColorData{\n        Color: tileColors[rand.Intn(len(tileColors))],\n    })\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L48\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/main.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/main.go#L48\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>This example is trivial, of course. The rendering system is not that universal if all it can do is draw tiles. We’re moving to a more complex project soon, but first, let’s add two more systems to this example.</p>\n<h3 id=\"breaking-tiles-with-a-click\">Breaking tiles with a click</h3>\n<p>To make the tiles a bit less boring, let’s add a way to <em>break</em> them: when you click a tile, it should fall down the screen.</p>\n<p>We’ll add two components:</p>\n<ul><li><code>Velocity</code>, so that the tiles move.</li><li><code>Rotation</code>, for a bit more dramatic visual effect.</li></ul>\n<pre><code>type VelocityData struct {\n    X float64\n    Y float64\n\n    Rotation float64\n}\n\nvar Velocity = donburi.NewComponentType[VelocityData]()\n\ntype RotationData struct {\n    Angle float64\n}\n\nvar Rotation = donburi.NewComponentType[RotationData]()</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L16\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L16\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>We’ll add a <code>VelocitySystem</code>, making the entities move. It’s a good example of a universal system in action. It updates the position and rotation of entities by the set values. We can forget it exists and set velocity on an entity we need to move.</p>\n<pre><code>func (v *VelocitySystem) Update(w donburi.World) {\n    for entry := range v.query.Iter(w) {\n        pos := Position.Get(entry)\n        rot := Rotation.Get(entry)\n        velocity := Velocity.Get(entry)\n\n        pos.X += velocity.X\n        pos.Y += velocity.Y\n        rot.Angle += velocity.Rotation\n    }\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L25\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/systems.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L25\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Now, we need a system for detecting clicks on the tiles. First, let’s somehow mark the entities that can be clicked, so it’s more explicit. We’ll create a <code>Clickable</code> component.</p>\n<p>This component has no data. We use it only to mark that the entity supports clicking on it. For components without data like this, we can use a shortcut from Donburi: a <em>tag</em>.</p>\n<pre><code>var Clickable = donburi.NewTag()</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L37\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/components.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/components.go#L37\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>We need to include this tag along with the new components when creating an entity:</p>\n<pre><code>tile := w.Create(Position, Rotation, Color, Velocity, Clickable)</code></pre>\n<p>The <code>ClickSystem</code> can look like this:</p>\n<pre><code>func NewClickSystem() *ClickSystem {\n    return &amp;ClickSystem{\n        query: donburi.NewQuery(\n            filter.Contains(Clickable, Velocity),\n        ),\n    }\n}\n\nfunc (c *ClickSystem) Update(w donburi.World) {\n    p, ok := pressedPoint()\n    if !ok {\n        return\n    }\n\n    for entry := range c.query.Iter(w) {\n        pos := Position.Get(entry)\n\n        if p.X &gt;= pos.X &amp;&amp; p.X &lt;= pos.X+TileSize &amp;&amp;\n            p.Y &gt;= pos.Y &amp;&amp; p.Y &lt;= pos.Y+TileSize {\n\n            velocity := Velocity.Get(entry)\n            velocity.X = randomRange(-1, 1)\n            velocity.Y = randomRange(1.5, 2.5)\n            velocity.Rotation = randomRange(-0.1, 0.1)\n\n            entry.RemoveComponent(Clickable)\n        }\n    }\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L80\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/tiles/systems.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/tiles/systems.go#L80\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>So once a mouse button is clicked (or the screen is tapped), we iterate over all clickable entities and check if they intersect with the pressed point. If so, we set a random velocity and rotation for the tile. That’s enough to get it moving, since the velocity system picks it up from there.</p>\n<p>Finally, we remove the <code>Clickable</code> component, so that it’s not possible to click a falling tile again.</p>\n<p>See the end result below:</p>\n<p><a href=\"https://threedotslabs.github.io/go-ecs-games/tiles/main.html\" rel=\"nofollow ugc noopener\">Open in a new tab</a></p>\n<p>I also updated the rendering system to take rotation into account. You can see the full source on <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/tree/main/tiles\" rel=\"nofollow ugc noopener\">GitHub</a>.</p>\n<p>Hopefully you got a general idea of how Donburi works so far, but such a simple project doesn’t show the benefits of ECS well. Let’s look at another project.</p>\n<h2 id=\"a-slightly-more-complete-game\">A slightly more complete game</h2>\n<p>We’ll simulate an aquarium, with the player controlling a friendly pufferfish. It grows by collecting bubbles and needs to avoid other fish around it. The player scores points for the bubbles and loses points by eliminating the poor fish.</p>\n<p>Try it yourself (control the pufferfish with WASD; no mobile controls, sorry!).</p>\n<p><a href=\"https://threedotslabs.github.io/go-ecs-games/pufferfish/main.html\" rel=\"nofollow ugc noopener\">Open in a new tab</a></p>\n<p>Assets by <a href=\"https://kenney.nl\" rel=\"nofollow ugc noopener\">Kenney</a>, my usual source of inspiration.</p>\n<p>I won’t describe the entire game step by step, but will mention new patterns I introduced there. The full source is on <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/tree/main/pufferfish\" rel=\"nofollow ugc noopener\">GitHub</a>.</p>\n<h3 id=\"project-structure\">Project structure</h3>\n<p>For a game this size, it makes sense to split it into packages. One level of packages should be enough.</p>\n<pre><code>├── archetype/\n│   └── ...\n├── assets/\n│   └── ...\n├── component/\n│   └── ...\n├── domain/\n│   └── ...\n├── engine/\n│   └── ...\n├── event/\n│   └── events.go\n├── game/\n│   └── game.go\n├── system/\n│   └── ...\n└── main.go</code></pre>\n<p><code>game</code> is the entry point, including the <code>Game</code> struct and the initial Donburi world.</p>\n<p><code>component</code> and <code>system</code> packages keep components and systems as described so far.</p>\n<p>I like to keep the names singular, so later I get self-explanatory <code>component.Velocity</code> and <code>system.Rendering</code> types.</p>\n<p><code>assets</code> keeps the assets loaded with <code>go:embed</code> for easier distribution. It’s a trivial one in this case, just loading all of them on import. For bigger games, it makes sense to add an asynchronous loader here.</p>\n<p>In the <code>engine</code> package, I keep common helper functions that don’t belong anywhere. Things like <code>Timer{}</code>, <code>RandomDuration()</code>, <code>Rect{}</code>, etc. Because they are universal (never specific to the game), it’s easy to copy-paste this package when starting a new game and use them right away.</p>\n<p>We’ll get to <code>archetype</code>, <code>domain</code>, and <code>event</code> soon.</p>\n<p>The order of imports goes something like this. A package can’t import anything above it.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/package-imports_hu27d42cac96554d7ba65d38cb7f66876f_78556_857x831_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"Package import order from top to bottom: game, system, event and archetype, component, domain, engine and assets\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<h3 id=\"position-rotation-and-scale\">Position, rotation, and scale</h3>\n<p>Donburi comes with the <code>Transform</code> component, which most entities need. It includes the basic data each object in 2D space has: position, rotation, and scale. We no longer need to define them ourselves, as we did in the tiles example.</p>\n<pre><code>import (\n    &quot;github.com/yohamta/donburi/features/math&quot;\n    &quot;github.com/yohamta/donburi/features/transform&quot;\n)\n\n// ...\n\nentry := w.Entry(w.Create(transform.Transform))\n\nt := transform.GetTransform(entry)\n\nt.LocalPosition = math.Vec2{X: 50, Y: 0}\nt.LocalRotation = 2\nt.LocalScale = math.Vec2{X: 2, Y: 2}</code></pre>\n<p>The 2D vector (<code>math.Vec2</code>) also comes from Donburi, and it’s just a pair of (X, Y) values. I described working with position, rotation, and scale in detail in <a href=\"https://threedots.tech/post/making-games-in-go/\" rel=\"nofollow ugc noopener\">the previous post</a>.</p>\n<h3 id=\"archetypes-constructors-for-entities\">Archetypes: constructors for entities</h3>\n<p>Working with components can get verbose, so I use a high-level API to simplify it. I keep it in the <code>archetype</code> package.</p>\n<p>The <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/main/pufferfish/archetype/entry.go\" rel=\"nofollow ugc noopener\">API</a> uses the builder pattern. <code>New()</code> creates a new entry with the <code>Transform</code> component, and <code>With()</code> adds more components.</p>\n<p>In practice, it looks like this:</p>\n<pre><code>cam := archetype.New(world).\n    With(component.Camera).\n    With(component.PositionLimit).\n    Entry()</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L84\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L84\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>For common objects that can be created in a few places, I also create constructors in the <code>archetype</code> package:</p>\n<pre><code>func NewFish(w donburi.World, pos math.Vec2) *donburi.Entry {\n    kind := engine.RandomFrom(fishKinds)\n    scale := engine.RandomFloatRange(domain.FishMinScale, domain.FishMaxScale)\n\n    fish := New(w).\n        WithPosition(pos).\n        WithSprite(component.SpriteData{\n            Image: kind.Sprite,\n            Layer: component.LayerBackground,\n        }).\n        WithScale(math.Vec2{\n            X: scale,\n            Y: scale,\n        }).\n        With(component.Velocity).\n        With(component.Drag).\n        With(component.PositionLimit).\n        With(component.Killable).\n        With(kind.AI).\n        With(component.Remains).\n        WithSpriteBounds().\n        Entry()\n\n    component.Remains.SetValue(fish, component.RemainsData{\n        Image: kind.Skeleton,\n    })\n\n    // ...\n\n    return fish\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/fish.go#L26\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/archetype/fish.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/fish.go#L26\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Now, creating a new fish is as simple as:</p>\n<pre><code>fish := archetype.NewFish(w, math.Vec2{X: 50, Y: 100})</code></pre>\n<p>For some common components like <code>Sprite</code>, I extend the builder so the API is even easier to use. For example, the <code>WithTimeToLive</code> method adds the <code>TimeToLive</code> component and sets its timer to the given duration. It’s easy to extend the API, thanks to keeping it part of the game instead of a generic library.</p>\n<h3 id=\"parents-and-children\">Parents and children</h3>\n<p>Transform supports parent-child relationships, which is super handy. When you make an entity a child of another entity, it’s easy to calculate its position, rotation, and scale, taking entities in the hierarchy into account. In other words, you can make it “follow” the parent.</p>\n<p>The <code>transform</code> package exposes an API for this:</p>\n<pre><code>transform.AppendChild(parent, child, false)\ntransform.SetParent(child, parent, false)\n\nparent, ok := transform.GetParent(child)\nchildren, ok := transform.GetChildren(parent)</code></pre>\n<p>Have you noticed that <code>Transform</code> uses <code>LocalPosition</code>, <code>LocalRotation</code>, and <code>LocalScale</code>? If the entity has no parent, its <em>local</em> position is the same as its <em>world</em> position. But once it has one, the local position is the position relative to the parent. That’s what the <code>false</code> argument to <code>AppendChild</code> and <code>SetParent</code> controls: with <code>true</code>, Donburi recalculates the local position so the child doesn’t move in the world.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/local-world-position_hu9dfb7f2c4327b25a58b5313d4f986107_61688_861x615_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"A parent at local and world position (10, 5) and its child at local position (5, 7) and world position (15, 12)\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>To read the world values, the <code>transform</code> package has functions that return the <em>world</em> position, rotation, and scale. “World” in this context means “Local value plus parent and all grandparents”.</p>\n<pre><code>pos := transform.WorldPosition(child)\nrotation := transform.WorldRotation(child)\nscale := transform.WorldScale(child)</code></pre>\n<p>In practice, this means every time we attach an entity as a child to another entity, we only need to worry about setting its local position. All systems using the world position will treat it as being <em>attached</em> to the parent.</p>\n<p>We use parent-child relationships when spawning a new bubble. We have a couple of <em>spawner</em> entities in the game world. They are invisible and create new bubbles around them.</p>\n<p>When a new bubble appears on a timer, we set its local position:</p>\n<pre><code>pos := math.Vec2{\n    X: engine.RandomFloatRange(-200, 200),\n    Y: engine.RandomFloatRange(-200, 200),\n}\n\nbubble := New(w).\n    WithParent(parent).\n    WithPosition(pos).\n    // ...</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/bubble.go#L41\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/archetype/bubble.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/bubble.go#L41\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Because the spawner is set as the parent, we can just get a random distance between -200 and 200, and the bubble will appear within that distance of the spawn point. If we move the spawners, the bubbles will follow them.</p>\n<h3 id=\"layers-and-the-camera\">Layers and the camera</h3>\n<p>The rendering system is more universal now. The key element is the <code>Sprite</code> component, representing an image we draw:</p>\n<pre><code>type Layer int\n\nconst (\n    LayerBackground Layer = iota\n    LayerPlayer\n    LayerForeground\n)\n\ntype SpriteData struct {\n    Image *ebiten.Image\n    Layer Layer\n    FlipX bool\n}\n\nfunc (s SpriteData) Order() int {\n    // Used by ordered query\n    return int(s.Layer)\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/sprite.go#L8\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/sprite.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/sprite.go#L8\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>We support layers. The lower layers get drawn first on the screen, so higher layers end up on top. The <code>Order()</code> method makes sprites work with Donburi’s ordered queries, which iterate over entities sorted by layer.</p>\n<p>Layers are just arbitrary numbers, but we define a few constants. We’ll have all fish in the background, the player on top of them, and the bubbles above everything else.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/layers_hu9ea9391b98069f33c884d4c10d20f1af_47706_986x662_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"Three overlapping layers: Background at the bottom, Player in the middle, and Foreground on top\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>We use a single <em>camera</em> that follows the player. We draw the entire game world on the <code>offscreen</code> image in memory. Then, we paint a portion of it onto the actual screen, offset by the camera position.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/camera_hu14e4b124f2a751995df0dcab070fec3b_82230_986x662_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"The camera rectangle around the player inside a larger game world, offset by X and Y from the world&#39;s origin\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<pre><code>cam, ok := r.cameraQuery.First(w)\nif !ok {\n    return\n}\ncamPos := transform.WorldPosition(cam)\n\nop := &amp;ebiten.DrawImageOptions{}\nop.GeoM.Translate(-camPos.X, -camPos.Y)\nscreen.DrawImage(r.offscreen, op)</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/rendering.go#L67\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/rendering.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/rendering.go#L67\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<h3 id=\"rendering-text\">Rendering text</h3>\n<p>Rendering text is similar to rendering sprites, but simpler. We use a new component:</p>\n<pre><code>type TextData struct {\n    Text string\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/text.go#L7\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/text.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/text.go#L7\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>We draw entities with this component the same way we draw sprites, but with text instead. This could be improved by extending the component data with things like text color, font size, alignment, etc.</p>\n<p>Because of the order of <em>drawers</em>, text will always appear on top of the sprites. For our use case, that’s good enough.</p>\n<pre><code>g.drawers = []Drawer{\n    system.NewRendering(),\n    system.NewTextRendering(),\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L56\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L56\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<h3 id=\"composition-in-practice\">Composition in practice</h3>\n<p>Here’s a comparison of some of the entities and components we use:</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/entity-components_huf8fc35784e20d320a26116b35fb9ac03_280931_1972x1508_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"Components of the Player, Fish, Bubble, and Camera entities: all have Transform, the player adds Input, Player, and Killer, the fish add Killable, Remains, and one of four AI components, bubbles add Collectable and Time To Live, and the camera adds Camera\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>Tip</p>\n<p>Components aren’t just buckets for data, but they should give you a clear idea of what can happen with the entity. Try to find names that clearly describe what the component represents.</p>\n<h3 id=\"movement-and-controls\">Movement and controls</h3>\n<p>We use a similar <code>Velocity</code> system to the one in the previous example.</p>\n<p>I wanted to make controls feel a bit like swimming, so there’s also the <code>Drag</code> system. It reduces the velocity of entities with the <code>Drag</code> component over time. This way, after you press a movement button, the player moves for a bit and gradually stops.</p>\n<p>Drag also works on other fish, but not on bubbles, which have constant upward velocity. This is an example of how you can control which entities a system handles, and which it doesn’t. <code>Drag</code> is a tag, so it enables or disables the behavior for the chosen entities. We could also dynamically add or remove it.</p>\n<h3 id=\"keeping-entities-within-world-boundaries\">Keeping entities within world boundaries</h3>\n<p>We use the same mechanism to limit the camera, player, and fish positions, so they never leave the world edges.</p>\n<pre><code>component.PositionLimit.SetValue(player, component.PositionLimitData{\n    Min: math.Vec2{},\n    Max: math.Vec2{X: domain.MapWidth, Y: domain.MapHeight},\n})</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/player.go#L36\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/archetype/player.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/archetype/player.go#L36\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>For the camera, we adjust the limit based on the screen dimensions:</p>\n<pre><code>component.PositionLimit.SetValue(cam, component.PositionLimitData{\n    Min: math.Vec2{X: 0, Y: 0},\n    Max: math.Vec2{X: domain.MapWidth - ScreenWidth, Y: domain.MapHeight - ScreenHeight},\n})</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L93\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L93\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Note how the limit system works the same for entities as different as the camera and the player, with a slight adjustment of the boundaries.\nWe don’t add the <code>PositionLimit</code> component to the bubbles, because they can <em>escape</em> upwards.</p>\n<h3 id=\"fish-behaviors\">Fish behaviors</h3>\n<p>I thought it would be fun to give each fish color a different behavior, like ghosts in Pac-Man:</p>\n<ul><li>Blue fish are idle, moving up and down and left and right just a bit.</li><li>Orange fish choose a cardinal direction and swim for a bit.</li><li>Red fish chase the player, then step away once they get close.</li><li>Green fish slowly swim towards the player, then quickly flee once they get close.</li></ul>\n<p>Each type needs a different state (timers and other data). Instead of using a single component, I decided to go with four, one for each AI type. But there’s still one system. I used a query that combines any of the components:</p>\n<pre><code>query: donburi.NewQuery(\n    filter.Or(\n        filter.Contains(component.IdleAI),\n        filter.Contains(component.RandomMovementAI),\n        filter.Contains(component.ChasePlayerAI),\n        filter.Contains(component.FleePlayerAI),\n    ),\n),</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L29\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/ai.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L29\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Then, I branch out:</p>\n<pre><code>for entry := range a.query.Iter(w) {\n    if entry.HasComponent(component.IdleAI) {\n        a.handleIdleAI(entry)\n    } else if entry.HasComponent(component.RandomMovementAI) {\n        a.handleRandomMovementAI(entry)\n    } else if entry.HasComponent(component.ChasePlayerAI) {\n        a.handleChasePlayerAI(w, entry)\n    } else if entry.HasComponent(component.FleePlayerAI) {\n        a.handleFleePlayerAI(w, entry)\n    } else {\n        panic(&quot;entity has AI component but no known AI type&quot;)\n    }\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L43\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/ai.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L43\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Four systems would work just as well. I chose a bit less boilerplate.</p>\n<h3 id=\"bounds-smaller-than-the-sprite\">Bounds smaller than the sprite</h3>\n<p><code>Bounds</code> is a component that represents the entity’s boundaries in the game world. For example, we use it to check collisions. It’s the entity’s 2D dimensions.</p>\n<pre><code>type BoundsData struct {\n    Width  float64\n    Height float64\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L9\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/bounds.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L9\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>The simplest way is to use the image size as bounds. But we create a separate component to have more control over the dimensions.</p>\n<p>We make the bounds a bit smaller than the image. This reduces the collision area. Otherwise, the player would collide with the fish by touching the transparent parts, which would be unintuitive and annoying.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/bounds_hu60ce5414acd4c87089abebda42cad176_59867_795x560_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"A fish and the pufferfish with dashed rectangles marking their bounds, smaller than the sprites, with the width and height labeled\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>We create a <code>Rect()</code> method that returns a struct filled with the entity’s position together with the bounds, taking <em>scale</em> into account.</p>\n<pre><code>func (d BoundsData) Rect(e *donburi.Entry) engine.Rect {\n    scale := transform.WorldScale(e)\n    pos := transform.WorldPosition(e)\n    w := d.Width * scale.X\n    h := d.Height * scale.Y\n    return engine.NewRect(pos.X-w/2, pos.Y-h/2, w, h)\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L15\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/bounds.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/bounds.go#L15\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>Taking scale into account matters because we’ll use different scales for the fish, and the player’s scale will change during gameplay. All logic related to the boundaries needs to consider this.</p>\n<p>Calling this method is a bit unusual because of how components work. The <code>BoundsData</code> struct keeps only the dimensions, so we also need to pass the entry to <code>Rect</code> to get the current position.</p>\n<pre><code>bounds := component.Bounds.Get(entry)\nrect := bounds.Rect(entry)\n\nif rect.Intersects(anotherRect) {\n    // ...\n}</code></pre>\n<p>There’s a trivial <code>Debug</code> system that flips a boolean debug flag. When the flag is on, the rendering system draws the bounds around the sprites.</p>\n<figure><img src=\"https://threedots.tech/post/making-games-in-go-ecs/images/debug-bounds_hub326aff574b5aa73059843be409c5849_324088_2112x1682_fill_q80_h2_lanczos_smart1_3.webp\" alt=\"The aquarium game with rectangles drawn around every fish and bubble\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>An easy way to visually debug the boundaries.</p>\n<h3 id=\"decoupling-systems-with-events\">Decoupling systems with events</h3>\n<p>Donburi supports <a href=\"https://academy.threedots.tech/knowledge/event/\" rel=\"nofollow ugc noopener\">events</a>. It’s a simple mechanism, as we still have one game loop running. We don’t do any asynchronous processing.</p>\n<p>Instead, we <em>publish</em> events in memory and process them each tick, which means we call all functions that have <em>subscribed</em> to them.</p>\n<p>I like working with events because they let you <a href=\"https://academy.threedots.tech/knowledge/event-driven-architecture/\" rel=\"nofollow ugc noopener\">decouple concepts</a> in the game. Many game elements are connected, and over time the logic becomes full of calls to different parts, which is hard to follow.</p>\n<p>Let’s consider the <code>Kill</code> system from our game. We look for intersections between a killer (the player object) and a killable (other fish). Once they intersect, we destroy the fish and reduce the player’s points.</p>\n<pre><code>func (k *Kill) Update(w donburi.World) {\n    for killerEntry := range k.killerQuery.Iter(w) {\n        for killableEntry := range k.killableQuery.Iter(w) {\n            killerBounds := component.Bounds.Get(killerEntry)\n            killableBounds := component.Bounds.Get(killableEntry)\n\n            if killerBounds.Rect(killerEntry).Intersects(killableBounds.Rect(killableEntry)) {\n                component.Destroy(killableEntry)\n\n                // TODO Take points out of player&#39;s score\n            }\n        }\n    }\n}</code></pre>\n<p>The thing is, adding scoring logic here feels beyond the responsibility of this system. It would work just fine, but note how <em>generic</em> the system is now. It doesn’t know anything about fish or the player. It just makes sure that a killer destroys a killable it intersects with.</p>\n<p>So we define a <code>Killed</code> event in the <code>event</code> package:</p>\n<pre><code>import &quot;github.com/yohamta/donburi/features/events&quot;\n\ntype KilledData struct {\n    Points int\n}\n\nvar Killed = events.NewEventType[KilledData]()</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/event/events.go#L13\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/event/events.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/event/events.go#L13\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>And publish it in the <code>Kill</code> system:</p>\n<pre><code>if killerBounds.Rect(killerEntry).Intersects(killableBounds.Rect(killableEntry)) {\n    component.Destroy(killableEntry)\n\n    event.Killed.Publish(w, event.KilledData{\n        Points: component.Killable.Get(killableEntry).Points,\n    })\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/kill.go#L35\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/kill.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/kill.go#L35\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>We define event handlers on systems, since that is where most of the game’s logic lives. The <code>Scoring</code> system subscribes to the <code>Killed</code> and <code>Collected</code> events.</p>\n<pre><code>func (s *Scoring) Subscribe(w donburi.World) {\n    event.Killed.Subscribe(w, s.onKilled)\n    event.Collected.Subscribe(w, s.onCollected)\n}\n\nfunc (s *Scoring) onKilled(w donburi.World, e event.KilledData) {\n    s.updateScore(w, e.Points)\n}\n\nfunc (s *Scoring) onCollected(w donburi.World, e event.CollectedData) {\n    s.updateScore(w, e.Points)\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/scoring.go#L25\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/scoring.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/scoring.go#L25\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>We call <code>Subscribe</code> once, right after creating the world. We process the events in the main <code>Update</code> method. Note that events also live in Donburi’s world.</p>\n<pre><code> func (g *Game) Update() error {\n     for _, s := range g.systems {\n         s.Update(g.world)\n     }\n\n+    events.ProcessAllEvents(g.world)\n\n     return nil\n }</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L122\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L122\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<h3 id=\"deferred-destroy\">Deferred <code>Destroy</code></h3>\n<p>To remove an entity from the world, you can call <code>entry.Remove()</code>. But another system down the stack might still have a leftover reference to it, and then your game will crash. You can check if the entity is valid with <code>entry.Valid()</code>, but it adds a lot of noise to the logic code.</p>\n<p>I kept running into this issue over and over, and finally changed the approach.</p>\n<p>Instead of removing the entities, we mark them as <em>destroyed</em> with a tag. We can use a helper method:</p>\n<pre><code>var Destroyed = donburi.NewTag()\n\nfunc Destroy(e *donburi.Entry) {\n    if !e.Valid() {\n        return\n    }\n    if !e.HasComponent(Destroyed) {\n        e.AddComponent(Destroyed)\n    }\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/destroyed.go#L7\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/destroyed.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/destroyed.go#L7\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>The <code>Destroy</code> system cleans up the destroyed entities, like a garbage collector. <code>RemoveRecursive</code> also removes all children in the hierarchy.</p>\n<pre><code>func (d *Destroy) Update(w donburi.World) {\n    for entry := range d.query.Iter(w) {\n        transform.RemoveRecursive(entry)\n    }\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/destroy.go#L22\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/destroy.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/destroy.go#L22\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>The order of systems usually doesn’t matter, but here it’s important. <code>Destroy</code> is the last system in the stack, to give other systems a chance to process the entity before it’s removed for good.\nNote the <code>Remains</code> system, which leaves a skeleton where a fish died. It queries destroyed entities and needs to run before they are removed for good.</p>\n<pre><code> g.systems = []System{\n     // ...\n     system.NewKill(),\n     system.NewTimeToLive(),\n     system.NewRemains(),\n+    system.NewDestroy(),\n }</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L41\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/game/game.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/game/game.go#L41\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<h3 id=\"game-rules-in-the-domain-package\">Game rules in the domain package</h3>\n<p>For a while, I looked for a good place to keep some of the game’s constants, like the movement speed, initial health points, etc. When you hardcode these values in systems, updating them is annoying.</p>\n<p>Similarly, there is often some logic inside systems that’s more related to the inherent game rules than how it works in Ebitengine or Donburi. For example, how some effects stack or how damage is calculated.</p>\n<p>I keep this kind of code in the <code>domain</code> package. I took the name from <a href=\"https://academy.threedots.tech/knowledge/ddd/\" rel=\"nofollow ugc noopener\">DDD</a> because it felt the most natural to me. The key is that it’s separate, doesn’t import any other game packages, and it’s easy to change and <a href=\"https://academy.threedots.tech/knowledge/unit-tests/\" rel=\"nofollow ugc noopener\">test</a>.</p>\n<pre><code>package domain\n\nimport &quot;time&quot;\n\nconst (\n    FishKillPenalty = -10\n\n    FishMinScale = 0.4\n    FishMaxScale = 1.2\n\n    ChaseFallBackDistance = 75.0\n    ChaseRange            = 400.0\n    FleeDistance          = 150.0\n\n    BubbleTimeToLive  = 60 * time.Second\n    RemainsTimeToLive = 3 * time.Minute\n)\n\nfunc FishSpeed(base float64, scale float64) float64 {\n    return base / scale\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/domain/fish.go#L5\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/domain/fish.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/domain/fish.go#L5\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>For example, we use the domain rule that “big fish swim slower” in a few spots in the fish AI system. If we wanted to change how it’s calculated, or what else it depends on, we’d change it in one place.</p>\n<pre><code>speed := domain.FishSpeed(engine.RandomFloatRange(0.7, 1.2), t.LocalScale.X)</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L159\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/system/ai.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/system/ai.go#L159\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>The <code>domain</code> package is a great place for all kinds of testing, since it’s <a href=\"https://academy.threedots.tech/knowledge/domain-layer/\" rel=\"nofollow ugc noopener\">pure logic</a> and doesn’t need the rest of the game engine to work.</p>\n<p>You could also build a way to change the domain constants live during gameplay for easier playtesting. Choosing these values is often key to making the game fun to play.</p>\n<h3 id=\"singletons-as-entities\">Singletons as entities</h3>\n<p>Sometimes, you need a single copy of an object to track data. For example, I keep the screen size and debug toggle in the <code>Settings</code> component. There’s always a single instance of it in the world, and I use a dedicated <code>MustFindSettings()</code> function to get it.</p>\n<pre><code>type SettingsData struct {\n    ScreenWidth  int\n    ScreenHeight int\n\n    Debug bool\n}\n\nvar Settings = donburi.NewComponentType[SettingsData]()\n\nvar settingsQuery = donburi.NewQuery(filter.Contains(Settings))\n\nfunc MustFindSettings(w donburi.World) *SettingsData {\n    entry, ok := settingsQuery.First(w)\n    if !ok {\n        panic(&quot;settings not found&quot;)\n    }\n\n    return Settings.Get(entry)\n}</code></pre>\n<p>Full source: <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/settings.go#L8\" rel=\"nofollow ugc noopener\">github.com/ThreeDotsLabs/go-ecs-games/pufferfish/component/settings.go</a></p>\n<p><a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/blob/8c61c990eb0de9885512b880bca1c42abd920c61/pufferfish/component/settings.go#L8\" rel=\"nofollow ugc noopener\">Full source</a></p>\n<p>An alternative would be to use a global variable. But I like to stick to the ECS primitives because the <code>world</code> is already passed everywhere, and it’s easy to query what you need from it.</p>\n<p>We could also cache these singletons inside systems instead of fetching them every tick. The problems start once you do something unusual, like restarting the level, loading a game, or testing with multiple world instances. I prefer to keep the systems completely stateless, so that the <code>world</code> you pass to <code>Update()</code> keeps the entire game state.</p>\n<p>Don’t overuse singletons. We have a single camera and player instance now, but it could take the game in an interesting direction if we added more. <strong>ECS works best when you don’t treat the entities as unique snowflakes.</strong></p>\n<h2 id=\"when-ecs-shines\">When ECS shines</h2>\n<p>Here’s an example of how the game can change with a few lines of code. Controlling the player works thanks to the <code>Input</code> component. Try adding it to the fish on collision, instead of destroying them:</p>\n<pre><code>-component.Destroy(killableEntry)\n+killableEntry.AddComponent(component.Input)\n+// Copy the component data over from the player\n+component.Input.SetValue(killableEntry, component.Input.GetValue(killerEntry))</code></pre>\n<p>The fish now start following the player’s moves. But they keep their AI, too, so we need to keep moving to keep them close. Maybe that’s an interesting mechanic? I didn’t plan it beforehand, but I came across it while experimenting with the components. <strong>Note we didn’t have to touch the systems at all, because they are generic enough to work with many component configurations.</strong></p>\n<h2 id=\"when-ecs-is-too-much\">When ECS is too much</h2>\n<p>As much as I like working with ECS, it’s not a silver bullet.\nIt works great in games that simulate many objects with similar behaviors, as we’ve seen so far.</p>\n<p>But for many projects, it can feel like too much boilerplate and code scattered with no benefit.</p>\n<p>You can’t open the entity’s code and read through its logic, because it’s spread across systems.</p>\n<p>It can be difficult to track bugs that happen when systems interact with each other. Not all logic can be captured as an elegant, standalone <code>Update</code> function.</p>\n<p>I sometimes choose a hybrid approach for entities that are an exception.\nA simple <code>Script</code> component with a custom <code>Update</code> function can work fine. I’ll just code the custom logic for the specific entity instead of forcing multiple systems to make it work.</p>\n<pre><code>type ScriptData struct {\n    Update func(entry *donburi.Entry)\n}</code></pre>\n<p>You can also run custom logic in Ebitengine’s <code>Update()</code> and <code>Draw()</code> methods next to the systems. Donburi is easy to plug in where you need it, so you don’t need to go all in. For example, you could keep the game’s UI out of it.</p>\n<h2 id=\"evolving-your-engine\">Evolving your engine</h2>\n<p>What I described above isn’t an up-front design I made up, but what I ended up with after making games with this architecture and tweaking the approach as I went. Don’t treat it as a definitive guide, but rather as a starting point, and take it from here.</p>\n<p>I like how polishing the approach made the next games easier. (Obviously, starting projects is way more fun than finishing them. 😅) It freed me from the constant “how to model this?” questions. Instead, I have some familiar ground to start with.</p>\n<p>Specifically, it’s easy to copy components and systems between games. Many, like rendering, are universal and can be slightly adjusted, so you never start from zero.</p>\n<h2 id=\"making-games-with-ai-agents\">Making games with AI agents</h2>\n<p>I’m experimenting a lot these days. I also tried making games with agents while keeping the architecture I’m used to. It’s a lot of fun to describe what you have in mind and have quite a polished version in front of you in minutes.</p>\n<p>But working this way makes you less involved in the project. As the game gets more complex, you no longer have a clear idea of how everything ties together. That may also be true with old-school typing, but I feel it happens sooner when using AI.</p>\n<p>Another downside is that it’s much more tempting to create new features (because it’s so quick) than to polish existing ones and playtest the game so it’s fun to play. Not a big deal if you’re just having fun. But I think there’s value in going through the whole process yourself, although I can’t yet name it precisely.</p>\n<p>Gamedev can get ridiculously complex, but many parts work the same way across games. To keep the games built by agents in a familiar structure, I boiled down the approach from my earlier Ebitengine and Donburi games into <em>patterns</em>: Markdown files that agents can follow.</p>\n<p>A couple of thoughts before you see the patterns:</p>\n<ul><li>These are regular Markdown files, not some specialized <em>skills</em>. I don’t think any more structure is needed: recent models are smart enough to pick them up with a one-line hint.</li><li>They are not some secret spells that will make a great game. <strong>They worked well for me because I already know the architecture and I feel good working in it.</strong></li><li>I did not review all of them. They’re not supposed to work as linters, but to give LLMs a general direction that I can verify if needed.</li><li>I coded the Tiles and Pufferfish games by hand (with pleasure!), so I didn’t use the patterns for them. They follow the same ideas, though.</li></ul>\n<p>You’ll find the files <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games/tree/main/patterns\" rel=\"nofollow ugc noopener\">in the patterns directory</a>.</p>\n<h2 id=\"more-examples\">More examples</h2>\n<p>You can find the full source for both games <a href=\"https://github.com/ThreeDotsLabs/go-ecs-games\" rel=\"nofollow ugc noopener\">on GitHub</a>.</p>\n<p>If you want to see the code for bigger projects, here are some (unfinished 🥴) games I built with the same approach:</p>\n<ul><li><a href=\"https://github.com/m110/a-night-in-innsmouth\" rel=\"nofollow ugc noopener\">A Night in Innsmouth</a>, a narrative game based on the prose of H. P. Lovecraft.</li><li><a href=\"https://github.com/m110/kingdoms\" rel=\"nofollow ugc noopener\">Kingdoms</a>, a strategy game with terrain generation.</li><li><a href=\"https://github.com/m110/witchcraft\" rel=\"nofollow ugc noopener\">Witchcraft</a>, a local battle arena with different classes and spells.</li></ul>\n<p>Thanks for reading and have fun making your own games! If you found it useful or would like to read more about some topic, let me know in the comments.</p>","headings":[{"level":2,"text":"Why bother with ECS?","id":"why-bother-with-ecs"},{"level":2,"text":"Entities, components, and systems","id":"entities-components-and-systems"},{"level":3,"text":"Working with Donburi","id":"working-with-donburi"},{"level":3,"text":"Introducing systems","id":"introducing-systems"},{"level":3,"text":"Drawing the tiles","id":"drawing-the-tiles"},{"level":3,"text":"Breaking tiles with a click","id":"breaking-tiles-with-a-click"},{"level":2,"text":"A slightly more complete game","id":"a-slightly-more-complete-game"},{"level":3,"text":"Project structure","id":"project-structure"},{"level":3,"text":"Position, rotation, and scale","id":"position-rotation-and-scale"},{"level":3,"text":"Archetypes: constructors for entities","id":"archetypes-constructors-for-entities"},{"level":3,"text":"Parents and children","id":"parents-and-children"},{"level":3,"text":"Layers and the camera","id":"layers-and-the-camera"},{"level":3,"text":"Rendering text","id":"rendering-text"},{"level":3,"text":"Composition in practice","id":"composition-in-practice"},{"level":3,"text":"Movement and controls","id":"movement-and-controls"},{"level":3,"text":"Keeping entities within world boundaries","id":"keeping-entities-within-world-boundaries"},{"level":3,"text":"Fish behaviors","id":"fish-behaviors"},{"level":3,"text":"Bounds smaller than the sprite","id":"bounds-smaller-than-the-sprite"},{"level":3,"text":"Decoupling systems with events","id":"decoupling-systems-with-events"},{"level":3,"text":"Deferred Destroy","id":"deferred-destroy"},{"level":3,"text":"Game rules in the domain package","id":"game-rules-in-the-domain-package"},{"level":3,"text":"Singletons as entities","id":"singletons-as-entities"},{"level":2,"text":"When ECS shines","id":"when-ecs-shines"},{"level":2,"text":"When ECS is too much","id":"when-ecs-is-too-much"},{"level":2,"text":"Evolving your engine","id":"evolving-your-engine"},{"level":2,"text":"Making games with AI agents","id":"making-games-with-ai-agents"},{"level":2,"text":"More examples","id":"more-examples"}]}}