1
\$\begingroup\$

The below example is creation of character Entity. My problem is do I always need to call these engine.createComponent(...class) to create a component? Or should I wrap these to another class that handles the creation of entities?

PooledEngine engine = new PooledEngine();

...

CharacterComponent character = engine.createComponent(CharacterComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
SizeComponent size = engine.createComponent(SizeComponent.class);
TransformComponent transform = engine.createComponent(TransformComponent.class);
PhysicsComponent physics = engine.createComponent(PhysicsComponent.class);

Entity entity = engine.createEntity();
entity.flag = Constants.CHARACTER;

entity.add(character);
entity.add(texture);
entity.add(size);
entity.add(transform);
entity.add(physics);

engine.addEntity(entity);
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

If you want the simplest method you could just use something along the lines of a Factory:

public class CharacterFactory
{
    public static Entity spawnCharacter(PooledEngine engine)
    {
        CharacterComponent character = engine.createComponent(CharacterComponent.class);
        TextureComponent texture = engine.createComponent(TextureComponent.class);
        SizeComponent size = engine.createComponent(SizeComponent.class);
        TransformComponent transform = engine.createComponent(TransformComponent.class);
        PhysicsComponent physics = engine.createComponent(PhysicsComponent.class);

        Entity entity = engine.createEntity();
        entity.flag = Constants.CHARACTER;

        entity.add(character);
        entity.add(texture);
        entity.add(size);
        entity.add(transform);
        entity.add(physics);

        engine.addEntity(entity);

        return entity;
    }
}

Then when you use it:

PooledEngine engine = new PooledEngine();

Entity bob = CharacterFactory.spawnCharacter(engine);
Entity alice = CharacterFactory.spawnCharacter(engine);

You might have to clean up one or two syntactic or semantic issues in the Java I wrote (I'm a C++ programmer, haven't used Java in a couple years) but this would be my first step until I needed a more complex management solution for Character creation, this works best when your Characters are all very similar and you can throw in extra parameters to get exactly the behavioral differences you are looking for.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .