Working with Entities

Accessing Components

Every behavior receives the entity it's attached to. Use it to read and modify components:

// Read-only access
const auto *t = e.get<Transform>();

// Mutable access (for modification)
auto *t = e.get_mut<Transform>();
t->position.y += 1.0f;

// Check if entity has a component
if (e.has<Camera>()) {
  // this entity has a camera
}

// Set/replace a component
e.set(Transform{{0, 1, 0}, {0, 0, 0}, {1, 1, 1}});
Warning

Always check the pointer before using it. get() and get_mut() return nullptr if the entity doesn't have that component.

Finding Other Entities

Look up entities by name using the ECS world:

void OnUpdate(flecs::entity e, Engine &engine, float dt) override {
  auto &world = engine.GetWorld();

  // Find an entity by name
  auto player = world.lookup("Player");
  if (player.is_valid()) {
    const auto *playerPos = player.get<Transform>();
    // use playerPos->position
  }

  // Find the main camera
  flecs::entity cam = engine.GetMainCamera();
}

Reading Components on Other Entities

auto target = engine.GetWorld().lookup("Enemy");
if (target.is_valid() && target.has<Transform>()) {
  const auto *enemyTransform = target.get<Transform>();
  float distance = glm::distance(
      e.get<Transform>()->position,
      enemyTransform->position);

  if (distance < 10.0f) {
    // enemy is close
  }
}

Modifying Components on Other Entities

auto door = engine.GetWorld().lookup("Door");
if (door.is_valid()) {
  auto *doorTransform = door.get_mut<Transform>();
  doorTransform->position.y += 3.0f * dt; // raise the door
}

Creating Entities at Runtime

void OnStart(flecs::entity e, Engine &engine) override {
  auto &world = engine.GetWorld();

  auto bullet = world.entity("Bullet");
  bullet.set(Transform{{0, 1, 0}, {0, 0, 0}, {0.1f, 0.1f, 0.1f}});
  bullet.set(RigidBody{RigidBody::Dynamic, 0.1f});
  bullet.set(Collider{ColliderShape::Sphere});
}

Iterating Over Entities

Use the Flecs each method to iterate over all entities with specific components:

void OnUpdate(flecs::entity e, Engine &engine, float dt) override {
  // Find all entities with PointLight
  engine.GetWorld().each([](flecs::entity light, PointLight &pl) {
    pl.intensity = 1.0f + 0.5f * std::sin(/* time */);
  });
}

Entity Identity

uint64_t id = e.id();           // numeric ID (used for physics)
const char *name = e.name();    // entity name (can be null)
bool alive = e.is_alive();      // check if entity still exists
bool valid = e.is_valid();      // check if handle is valid