Entities
Entities are the "game objects" or "model entities" in applications that use Ark. In effect, an entity is just an ID that can be associated with Components, which contain the entity's properties or state variables.
Creating entities
An entity can only exist in a World, and thus can only be created through a World.
Here, we use new_entity! to create an entity with a Position and a Velocity components. Note that component values are passed as a tuple!
entity = new_entity!(world, (
Position(100, 100),
Velocity(0, 0),
))Components can be added to and removed from the entity later. This is described in the next chapter.
Often, multiple entities with the same same set of components are created at the same time. For that sake, Ark provides batch entity creation, which is much faster than creating entities one by one. There are different ways to create entities in batches:
From default component values using new_entities!. Here, we create 100 entities, all with the same Position and Velocity:
new_entities!(world, 100, (
Position(100, 100),
Velocity(0, 0),
))This may be sufficient in some use cases, but most often we will use a second approach:
From component types with subsequent manual initialization using the macro @new_entities!:
for (entities, positions, velocities) in @new_entities!(world, 100, (Position, Velocity))
for i in eachindex(entities)
positions[i] = Position(i, i)
velocities[i] = Velocity(0, 0)
end
endThe nested loop shown here will be explained in detail in the chapter on Queries, which work in the same way at the Batch iterator that is returned from @new_entities! and that is used here.
Note that with the second approach, all components of all entities should be set as they are otherwise uninitialized.
Removing entities
Removing an entity from the World is as easy as this:
remove_entity!(world, entity)Alive status
Entities can be safely stored, e.g. in the Components of other entities to represent relationships. However, as they may have been removed from the world elsewhere, it may be necessary to check whether an entity is still alive:
if is_alive(world, entity)
# ...
endZero entity
There is a reserved zero_entity that can be used as a placeholder for "no entity". The zero entity is never alive. the function is_zero can be used to determine whether an entity is the zero entity:
if is_zero(entity)
# ...
end