C++: Designing a component-based entity system - advanced problems

Jarnstrom picture Jarnstrom · Feb 25, 2011 · Viewed 10.1k times · Source

In my game engine, that is written in C++, I've moved away from the classical hierarchical entity system and build up a component-based one. It works roughly in this way:

An entity is merely a container for components. Some example components are: Point, Sprite, Physics, Emitter.

Each entity can hold at most one component of each type. Some component depend on another, like Physics and Sprite depend on Point, because they need a position and angle delivered by it.

So everything works fine with the component system, but now I have trouble implementing more specialized entities, like:

  • A camera, which needs additional functions to handle movement and zoom
  • A player, which needs support to receive input from the user and move

Now, I could easily solve this with inheritance. Just derive the camera from the entity and add the additional zoom functions and members. But this simply feels wrong.

My question:

  • How can I solve the problem of specialized entities with a component system in C++?

Answer

ltjax picture ltjax · Feb 25, 2011

You seem to be doubting the IS-A relationship here. So why not make it a HAS-A relationship? Instead of being an entity, the camera and the player could be objects that have an entity (or a reference to the entity), but exist outside of your component-system. That way, you can easily keep the uniformity and orthogonality of your component system.

This also fits nicely with the meaning of those two examples (camera/player) as 'glue' objects. The player glues the entity system to the input system and acts as a controller. The camera glues the entity system to the renderer and acts as a kind of observer.