Cookbook
Minimal World
Section titled “Minimal World”ecs_init();ecs_entity_t entity = ecs_new();ecs_fini();ecs::init();auto entity = ecs::entity::create();ecs::fini();Game Loop with Time
Section titled “Game Loop with Time”ECS_RESOURCE(Time, { float dt; });ECS_COMPONENT(Position, { float x; });ECS_COMPONENT(Velocity, { float x; });
static void Move(ecs_iter_t *it) { const Time *time = ecs_get_resource_read(Time); Position *p = ecs_field(it, 0); const Velocity *v = ecs_field(it, 1); for (uint32_t i = 0; i < it->count; i++) p[i].x += v[i].x * time->dt;}struct Time { float dt; };struct Position { float x; };struct Velocity { float x; };
ecs::set_resource(Time{ .dt = 0.016f });ecs::system("Move").each([](ecs::res<const Time> time, Position &p, const Velocity &v) { p.x += v.x * time->dt;});Parent and Child
Section titled “Parent and Child”ecs_entity_t parent = ecs_new();ecs_entity_t child = ecs_new();ecs_relate(child, ChildOf, parent);auto parent = ecs::entity::create();auto child = ecs::entity::create().child_of(parent);ChildOf cascades deletion: killing the parent also kills its children.
Optional Component Query
Section titled “Optional Component Query”ecs_query_id_t q = ecs_query({ .components = { ecs_inout(Position), ecs_in_optional(Velocity) },});auto query = ecs::query() .require<Position>() .optional<Velocity>();The callback can receive an optional field:
ecs_query_each(it, i, ecs_inout(Position), ecs_in_optional(Velocity)) { Position *position = ecs_field(&it, 0); const Velocity *velocity = ecs_field(&it, 1); if (velocity) position[i].x += velocity[i].x;}ecs::query().require<Position>().each( [](Position &position, ecs::optional<const Velocity> velocity) { if (velocity) position.x += velocity->x; });React to a Component Set
Section titled “React to a Component Set”#include <stdio.h>
static void OnPositionSet(ecs_observer_event_t *event) { const Position *incoming = event->trigger_data; printf("position.x = %f\n", incoming->x);}
ecs_observer({ .on = EcsOnSet, .query.components = { ecs_in(Position) }, .callback = OnPositionSet,});#include <iostream>
ecs::observe<ecs::OnSet>().each([](const Position &position) { std::cout << position.x << '\n';});Pause Entities with Disabled
Section titled “Pause Entities with Disabled”ecs_add(entity, Disabled);ecs_remove(entity, Disabled);entity.disable();entity.enable();Normal queries skip disabled entities. Add ecs_filter(Disabled) to match them
explicitly.