Skip to content

Entity Component System (ECS)

acoox edited this page Apr 22, 2021 · 10 revisions

Introduction

Almost everything that exists in the game is an entity, from the player and NPCs to the map terrain and UI. An entity doesn't do much on it's own, but acts as a container to add components to. This is a common pattern in game development called an Entity Component System (ECS).

Each component is responsible for one piece of functionality. We can make an entity do something interesting with the right combination of components. For example, to create a tree:

public static Entity createTree() {
    Entity tree = new Entity()
        .addComponent(new TextureRenderComponent("images/tree.png"))
        .addComponent(new PhysicsComponent())
        .addComponent(new ColliderComponent());
    return tree;
  }
  1. We start with a new entity
  2. We add a TextureRenderComponent which draws the tree texture on screen
  3. We add a PhysicsComponent which lets the tree use game physics
  4. We add a ColliderComponent which adds a rectangular collider around the tree, so other physics entities can't walk through it.

A simple player entity might look like:

public static Entity createPlayer()
  Entity player = new Entity()
    .addComponent(new TextureRenderComponent("images/tree.png"))
    .addComponent(new PlayerMovementComponent())
    .addComponent(new InventoryComponent())
    .addComponent(new CombatComponent());

We can reuse the same texture render component that we used for the tree, but also add player-specific components to control movement, give the player an inventory, and give them combat capabilities (e.g. health and attack damage).

Clone this wiki locally