alecthomas / entityx

EntityX - A fast, type-safe C++ Entity-Component system
MIT License
2.21k stars 295 forks source link

Inherited Component Polymorphism? #241

Closed jasonmeverett closed 3 years ago

jasonmeverett commented 3 years ago

Let's say I have a base component type:

struct Moveable  : public Component<Moveable>
{
    virtual void Update() = 0;
}

And I'd like to customize the component as follows:

struct MyMoveable : public Moveable
{
    void Update() override;
}

Then, I'd like to be able to get a list of all Moveable types as:

ComponentHandle<Moveable> MoveableComponent;
for(entityx::Entity entity : es.entities_with_components(MoveableComponent))
{
    // In here, I want access to MyMoveable.
}
alecthomas commented 3 years ago

Hi there. This is a fairly common misconception of how ECS works (see #171 and #42 for example). You do not want to use inheritance with ECS components at all. Instead of thinking of each component as a distinct class hierarchy, think of each entity as the composition of all the features you want that entity to have. So in your example you might have an Updateable and a Moveable component and you would do the following:

ComponentHandle<Moveable> MoveableComponent;
ComponentHandle<Updateable> UpdateableComponent;
for(entityx::Entity entity : es.entities_with_components(MoveableComponent, UpdateableComponent))
{
}
jasonmeverett commented 3 years ago

This is great insight. Thanks for the help!