Building an ECS in TypeScript
What is an ECS?
PrefacePermalink to “Preface”
This series is intended to be a simple walkthrough of building an ECS-based game engine in TypeScript. It’s based off my work on Fallgate, a small 2D action-adventure game I built with my friend Cooper over about two years of evenings and weekends.
So, what is an ECS?Permalink to “So, what is an ECS?”
ECS stands for entity component system. It is a design pattern used when programming games.
It works this way: you have Entities, Components, and Systems. (I’ll capitalize these throughout.)
Entities represent any game object, like the player, or a tree, or a spell. Each entity is just an ID number, like 42.
Components are data associated with Entities. For example, the player Entity might have several Components, like a
PositionComponent that holds its world coordinates, a
PlayerInputComponent that stores the latest controller input, and a
SpriteComponent that holds data for how to draw the player. Think of Components as bags of data, like JSON files.
Later on, we’ll break this rule of “Components are just data” and squeeze some a little bit of code into them. But “Components are just data” is the right conceptual model.
Systems are the actual code. They contain the game logic. Each System—and this is the important bit—selects all Entities which contain at least the set of required components. For example, a
RendererSystem could select all entities that have both a
SpriteComponent, and would draw each
You might already see why a System may be interested in additional Components. For example, the
RendererSystem may check whether the Entity also has a
DamagedComponent on it, indicating the Entity has recently taken damage. If so, it could render the
Spritewith a red tint.
ECS VisualizationPermalink to “ECS Visualization”
This ECS visualization demonstrates the core concept of Systems: selecting Entities that Contain at least their required Components. Under-the-hood, the visualization is powered by the ECS that we’ll build in this series.
Try clicking on “add/remove entity” randomly generate/remove entities.
Try hovering over the System areas to show the Systems selecting all Entities that match their set of required Components.