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

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

c++如何实现一个简单的ECS架构_c++游戏开发实体组件系统【设计模式】-第1张图片-佛山资讯网

用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 容器(避免非连续内存)。例如:

立即学习“C++免费学习笔记(深入)”;

struct Position {
    float x = 0.f, y = 0.f;
};
<p>struct Velocity {
float dx = 0.f, dy = 0.f;
};</p><p>struct Renderable {
const char* texture_name = nullptr;
};</p>

登录后复制

关键点:

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

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

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

struct MovementSystem {
    std::vector<Position>& positions;
    std::vector<Velocity>& velocities;
<pre class='brush:php;toolbar:false;'>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;
    }
}

登录后复制

};

标签: ai c++ 游戏开发 red

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~