c++如何实现一个简单的ECS架构_c++游戏开发实体组件系统【设计模式】

ECS架构核心是实体为纯ID、组件为POD数据、系统为无状态函数;Entity是uint32_t包装,Component用连续vector存储并按ID对齐,System直接遍历对应数组执行逻辑,World统一管理生命周期与调度。

用C++实现一个简单的ECS(Entity-Component-System)架构,核心是把数据(Component)和逻辑(System)彻底分离,实体(Entity)只作为ID存在。不依赖复杂模板或宏,也能写出清晰、可扩展、缓存友好的基础版本。

实体:轻量ID,不存数据

Entity 就是一个无符号整数(如 uint32_t),用于唯一标识一个游戏对象。它本身不包含任何成员变量,也不继承任何类——避免虚函数开销和内存碎片。

可以加一层简单包装防止误用:

struct Entity {
    uint32_t id;
    explicit Entity(uint32_t i) : id(i) {}
    bool operator==(const Entity& other) const { return id == other.id; }
};

组件:纯数据结构,无逻辑

Component 是 POD(Plain Old Data)类型:只有 public 成员变量,没有虚函数、构造/析构逻辑、指针或 STL 容器(避免非连续内存)。例如:

struct Position {
    float x = 0.f, y = 0.f;
};

struct Velocity { float dx = 0.f, dy = 0.f; };

struct Renderable { const char* texture_name = nullptr; };

关键点:

  • 每个组件类型对应一个独立的 std::vector(即“组件数组”),保证内存连续
  • vector 下标与 Entity ID 对齐(例如 entity.id == 5,则 Position[5] 就是它的位置)
  • 空槽位用特殊值(如 -1)或单独的活跃标志位管理,避免 vector 删除导致 ID 错位

系统:遍历匹配组件,执行逻辑

System 不持有 Entity 或 Component 实例,只在运行时按需访问组件数组。例如移动系统:

struct MovementSystem {
    std::vector& positions;
    std::vector& velocities;
void update(float dt) {
    size_t n = std::min(positions.size(), velocities.size());
    for (size_t i = 0; i < n; ++i) {
        positions[i].x += velocities[i].dx * dt;
        positions[i].y += velocities[i].dy * dt;
    }
}

};

实际中可用标签(Tag)或位掩码(Archetype)加速查询,但最简版直接遍历对齐数组即可。

系统之间无依赖顺序,靠手动调用顺序控制(如先 update Input → Movement → Collision → Render)。

世界(World):统一管理容器与生命周期

World 是 ECS 的调度中心,负责:

  • 分配/回收 Entity ID(用 freelist 或 atomic counter)
  • 按类型维护组件存储(如 std::unordered_map> + 类型擦除,或模板化 registry)
  • 提供 add_component/remove_component/get_component 接口
  • 持有所有 System 并提供 update() 入口

简易 registry 示例(不依赖 type_index):

template
struct ComponentStorage {
    std::vector data;
    std::vector alive; // 标记该槽是否有效
void grow_to(size_t n) {
    if (data.size() < n) {
        data.resize(n);
        alive.resize(n, false);
    }
}

T& get(Entity e) { return data[e.id]; }
void set(Entity e, const T& v) {
    grow_to(e.id + 1);
    data[e.id] = v;
    alive[e.id] = true;
}

};

struct World { ComponentStorage positions; ComponentStorage velocities; // ... 其他组件

Entity create_entity() {
    // 简单线性分配(生产环境建议 freelist)
    return Entity(next_id++);
}

void update(float dt) {
    movement_system.update(dt);
    // ...
}

private: uint32_t next_id = 0; MovementSystem movement_system{positions.data, velocities.data}; };

基本上就这些。不需要反射、不强制用宏、不绑定特定框架——C++11 起就能写。重点是守住“组件即数据、系统即函数、实体即ID”的边界,后续再按需加入 archetype、事件总线、多线程任务调度等增强特性。