Search code examples
javalibgdxentity-component-system

What is the proper way of creating an entity in libgdx ashley ecs framework pooled engine?


// GameWorld
PooledEngine engine = new PooledEngine();

// Gun class
class Gun {
   publc Gun(Entity entity) {
        createComponents();
        addComponents();
   }

   public Entity getEntity();
}

// Option 1
Gun gun = new Gun(engine.createEntity());
engine.addEntity(gun.getEntity());

// Option 2 or a simple method inside EntityFactory class
public Entity createGun() {
    Entity gun = engine.createEntity();
    // components creation here
    ..
    engine.addEntity(gun);
    return gun;
}

Question which one is the better way of creating an Entity made from the PooledEngine?

  • option 1, I create a new class called Gun then handle the creation of components there.
  • option 2, Inside the EntityFactory class add new method called createGun()

    class EntityFactory {
     // constructor 
     public void build() {
        // Option 1
        Gun gun = new Gun(engine.createEntity());
        // where I can call gun.fire(), gun.reload(), gun.dispose, and so on..
        engine.addEntity(gun.getEntity());
    
    
        // Option 2
        Entity gun = createGun();
        engine.addEntity(gun);
     }
    
     public Entity createGun() {
        Entity gun = engine.createEntity();
        // components creation here
        ...
        engine.addEntity(gun);
        return gun;
     }
    }
    
    EntityFactory factory = new EntityFactory(world, engine);
    factory.build();
    

Solution

  • I'd prefer the second method via an EntityFactory.

    Explanation:

    • Whereas the EntityFactory is a clean representation of the common factory pattern, you Gun looks like a builder pattern but with just one method for creating an Entity. So it makes no sense to use a new instance for every Entity creation as you store no building state in the instance.

    • Your Gun class is just a wrapper for an Entity. But if you get an Entityfrom engine.getEntitiesFor(Family... you cannot get it's Gun wrapper. So you cannot really use it for anything in your engine's systems.

    • If your EntityFactory gets too complex and long, I'd recommend to split it into a GunFactory, BananaFactory and so on.