EnTT 是一个用现代 C++ 编写的、轻量级、头文件式(header-only)的 ECS 库

EnTT 的 ECS 实现基于 稀疏集(sparse set)

#include <entt/entt.hpp>
#include <iostream>

// 定义组件
struct Position {
    float x, y;
};

struct Velocity {
    float dx, dy;
};

// 定义系统
void Update(entt::registry& registry, float dt) {
    // 获取所有具有 Position 和 Velocity 的实体
    auto view = registry.view<Position, Velocity>();
    for (auto entity : view) {
        // 获取组件
        auto& pos = view.get<Position>(entity);
        auto& vel = view.get<Velocity>(entity);
        // 更新位置
        pos.x += vel.dx * dt;
        pos.y += vel.dy * dt;
        std::cout << "Entity at (" << pos.x << ", " << pos.y << ")\n";
    }
}

int main() {
    // 创建注册表(registry),管理实体和组件
    entt::registry registry;

    // 创建一个实体
    auto entity = registry.create();
    // 添加组件
    registry.emplace<Position>(entity, 0.0f, 0.0f);
    registry.emplace<Velocity>(entity, 1.0f, 1.0f);

    // 模拟几帧更新
    for (int i = 0; i < 3; ++i) {
        update(registry, 0.1f);
    }

    return 0;
}