// 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
?
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();
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 Entity
from 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.