Component operations
Components contain the data associated to your game or simulation entities. This chapter explains how to to manipulate them. For general information on components, see section Components in chapter Concepts.
Component mappers
Component mappers ecs.Map1
, ecs.Map2
etc.
are helpers that allow to create entities with components,
to add components to entities, and to remove components from entities.
They are parametrized by the component types they handle.
1// Create a component mapper.
2mapper := ecs.NewMap2[Position, Velocity](&world)
3
4// Create an entity with components.
5entity1 := mapper.NewEntity(
6 &Position{X: 0, Y: 0},
7 &Velocity{X: 1, Y: -1},
8)
9
10// Create an entity without components.
11entity2 := world.NewEntity()
12// Add components to it.
13mapper.Add(
14 entity2,
15 &Position{X: 0, Y: 0},
16 &Velocity{X: 1, Y: -1},
17)
18// Remove components.
19mapper.Remove(entity2)
20
21// Remove the entities.
22world.RemoveEntity(entity1)
23world.RemoveEntity(entity2)
In this example, the 2
in ecs.NewMap2
denotes the number of mapped components.
Unfortunately, this is required due to the limitations of Go’s generics.
In addition to ecs.Map1
, ecs.Map2
, etc., there is ecs.Map
.
It is a dedicated mapper for a single component and provides a few additional methods.
Component mappers can also be used to access components for specific entities:
1// Create a component mapper.
2mapper := ecs.NewMap2[Position, Velocity](&world)
3
4// Create an entity with components.
5entity1 := mapper.NewEntity(
6 &Position{X: 0, Y: 0},
7 &Velocity{X: 1, Y: -1},
8)
9
10// Get mapped components for an entity.
11pos, vel := mapper.Get(entity1)
12
13_, _ = pos, vel
Important
The component pointers obtained should never be stored outside of the current context, as they are not persistent inside the world.
Component exchange
Adding and removing components are relatively costly operations, as entities and their components must be moved between archetypes. It is most efficient to perform component additions and removals in a single operation, instead of using multiple operations.
For that sake, Ark provides ecs.Exchange1
, ecs.Exchange2
etc.,
to do additions and removals in one go.
It adds the components given by the generics, and removes those specified with ecs.Exchange2.Removes
.
1// Create an entity with components.
2mapper := ecs.NewMap2[Position, Velocity](&world)
3entity := mapper.NewEntity(&Position{}, &Velocity{})
4
5// Create an exchange helper.
6exchange := ecs.NewExchange1[Altitude](&world).
7 Removes(ecs.C[Position](), ecs.C[Velocity]())
8
9exchange.Exchange(entity, &Altitude{Z: 100})