C++如何实现一个简单的实体组件系统(ECS)?

来源:Android社区作者:小何头衔:草根站长
导读:本期聚焦于小伙伴创作的《C++如何实现一个简单的实体组件系统(ECS)?》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C++如何实现一个简单的实体组件系统(ECS)?》有用,将其分享出去将是对创作者最好的鼓励。

实体组件系统(ECS)是一种常用的游戏架构模式,它将游戏对象拆分为实体、组件和系统三个核心部分。实体只是一个唯一标识,组件是附加在实体上的数据,系统则负责处理具备某些组件的实体集合。下面我们用C++实现一个最基础的ECS框架。

C++如何实现一个简单的实体组件系统(ECS)?

基础结构设计

首先定义实体类型和组件基类。实体使用整数ID表示,所有组件都继承自一个空基类以便统一存储。

#include <iostream>
#include <vector>
#include <unordered_map>
#include <memory>

// 实体类型:使用整数作为唯一ID
using Entity = int;

// 组件基类
struct Component {
    virtual ~Component() = default;
};

// 具体组件:位置组件
struct PositionComponent : Component {
    float x = 0.0f;
    float y = 0.0f;
};

// 具体组件:速度组件
struct VelocityComponent : Component {
    float vx = 0.0f;
    float vy = 0.0f;
};

实体与组件管理

我们需要一个世界类来管理所有实体以及它们绑定的组件。这里使用映射表按组件类型存储。

class World {
public:
    // 创建新实体
    Entity createEntity() {
        Entity e = nextEntityId++;
        entities.push_back(e);
        return e;
    }

    // 为实体添加组件
    template<typename T>
    void addComponent(Entity e, T* comp) {
        components[typeid(T).hash_code()][e] = std::shared_ptr<Component>(comp);
    }

    // 获取实体组件
    template<typename T>
    T* getComponent(Entity e) {
        auto& map = components[typeid(T).hash_code()];
        auto it = map.find(e);
        if (it != map.end()) {
            return static_cast<T*>(it->second.get());
        }
        return nullptr;
    }

    // 判断实体是否拥有某组件
    template<typename T>
    bool hasComponent(Entity e) {
        return getComponent<T>(e) != nullptr;
    }

    std::vector<Entity> entities;
private:
    Entity nextEntityId = 0;
    std::unordered_map<size_t, std::unordered_map<Entity, std::shared_ptr<Component>>> components;
};

系统实现

系统遍历拥有相关组件的实体并执行逻辑。下面实现一个移动系统,它更新带位置和速度组件的实体。

class MovementSystem {
public:
    void update(World& world, float dt) {
        for (Entity e : world.entities) {
            if (world.hasComponent<PositionComponent>(e) &&
                world.hasComponent<VelocityComponent>(e)) {
                PositionComponent* pos = world.getComponent<PositionComponent>(e);
                VelocityComponent* vel = world.getComponent<VelocityComponent>(e);
                pos->x += vel->vx * dt;
                pos->y += vel->vy * dt;
            }
        }
    }
};

使用示例

把上面的代码组合起来,就可以创建一个世界、生成实体并运行系统。

int main() {
    World world;
    MovementSystem moveSys;

    Entity player = world.createEntity();
    world.addComponent<PositionComponent>(player, new PositionComponent());
    world.addComponent<VelocityComponent>(player, new VelocityComponent());

    world.getComponent<VelocityComponent>(player)->vx = 1.0f;
    world.getComponent<VelocityComponent>(player)->vy = 2.0f;

    moveSys.update(world, 0.1f);

    PositionComponent* p = world.getComponent<PositionComponent>(player);
    std::cout << "Player position: " << p->x << ", " << p->y << std::endl;
    return 0;
}

小结

以上代码展示了一个极简的C++实体组件系统。实际项目中通常会使用更复杂的组件存储方式(如按类型分组的连续数组)来提升缓存命中率,也会引入事件机制和系统调度器。理解这个基础模型后,你可以更容易地阅读Unity DOTS或Entt等成熟ECS库的设计思路。

ECSC++游戏架构实体组件系统修改时间:2026-07-26 08:21:10

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。