Entity-Component Systems


Entity-Component systems are one approach to building complex systems, like games. Here’s a few comments about the entity-component system I built for Moonman: http://forums.tigsource.com/index.php?topic=21997.msg1180610#msg1180610


So, are you using templates in your code? I saw this thread, https://forums.tigsource.com/index.php?topic=50787.0 and some of the metaprogramming went right over my head. I understand the concept however, I’m having a difficult time implementing it however.


I do but they are unnecessary. Is there anything in particular you don’t understand?

A component system could be as simple as this:

struct Physics { double x, y; };
struct Entity { ID physics; };
struct EntitySystem {
   vector<Entity> entities;
   vector<Physics> physics;
class PhysicsSystem {
void update(){
   for (auto& ph: physics){
   // update ph.x, ph.y based on physics rules


I guess what stumps me the most is what the ID of the entity is. if you store it as ID, is that just another struct? or should you assign it a value? Or, because it is an entity I guess it has no values, so wouldn’t doing that be wrong? Should I treat the ID as another component?


Well there’s no right or wrong way, but I can explain what I do:

what the ID of the entity is

This is just a unique identifier for the entity. In Moonman it’s an integer. So a Moonman entity might have ID=7, a plant might have ID=645. Another plant may have ID=646.

Every entity and component gets an ID, so Moonman entity might have ID=7, but then it also has a whole bunch of components, each with their own IDs. E.g.,

Moonman: 7
   Physics: 5
   SpriteRenderer: 105
   Info: 3
   Inventory: 3

The IDs just look up into the entity or component containers. E.g.,

Entity& getEntity(ID id){
  return entitySystem.entities[id];

Physics& getPhysics(ID id){
  return entitySystem.physics[id];

void doSomething(ID){ 
  Entity& moonman = getEntity(moonmanId);
  Physics& physics = getPhysics(moonman.physics);
  physics.x  += 1;

It ends up being a lot more complicated than this when you want to optimise things, but that’s the basic idea behind the way I do it.


Ohh okay. I guess I was over complicating it in my head. Thanks for taking time to explain it to me. One last question though, Would you give components and entities separate ID’s? or all in one list?


It depends, I think the IDs should be all separate. E.g., your entity could have ID=1, and it could have a physics with ID=1, an inventory with ID=1, and an AIcontroller with ID=1. Each ID indexes into it’s own list of things.

If you’re not concerned about performance then it’s really simple to build a system.


Alright then, thanks a lot for the help! And Moonman looks awesome!


No problem, let me know how your design goes! :slight_smile: