在libgdx ashley ecs框架池化引擎中创建实体的正确方法是什么?

时间:2016-07-12 09:08:34

标签: java libgdx amazon-ecs

// 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;
}

问题哪一个是从Entity创建PooledEngine的更好方法?

  • 选项1,我创建了一个名为class的新Gun,然后在那里处理组件的创建。
  • 选项2,在EntityFactory class内添加名为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();
    

1 个答案:

答案 0 :(得分:1)

我更喜欢通过EntityFactory获得第二种方法。

说明:

  • 虽然EntityFactory是公共工厂模式的干净表示,但Gun看起来像builder pattern,但只有一种创建Entity的方法。因此,在每个Entity创建中使用新实例是没有意义的,因为在实例中不存储构建状态。

  • 您的Gun类只是Entity的包装器。但是,如果您从Entity获得engine.getEntitiesFor(Family...,则无法获得Gun包装。因此,您无法真正将其用于引擎系统中的任何内容。

  • 如果您的EntityFactory过于复杂且过长,我建议将其拆分为GunFactoryBananaFactory,依此类推。

相关问题