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

用C++实现一个简单的ECS(Entity-Component-System)架构,核心是把数据(Component)和逻辑(System)彻底分离,实体(Entity)只作为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>关键点:
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;
}
}};
实际中可用标签(Tag)或位掩码(Archetype)加速查询,但最简版直接遍历对齐数组即可。
系统之间无依赖顺序,靠手动调用顺序控制(如先 update Input → Movement → Collision → Render)。
World 是 ECS 的调度中心,负责:
简易 registry 示例(不依赖 type_index):
template<typename T>
struct ComponentStorage {
std::vector<T> data;
std::vector<bool> alive; // 标记该槽是否有效
<pre class='brush:php;toolbar:false;'>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
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、事件总线、多线程任务调度等增强特性。
以上就是c++++如何实现一个简单的ECS架构_c++游戏开发实体组件系统【设计模式】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号