在下面的代码方法中,我测试了创建和删除实体,因为我打算以这种方式创建子弹池。
public void build () {
Entity bulletTest1 = createBullet(0,0); // works perfectly but
removeEntity(bulletTest1); // after engine remove this bulletTest1 entity then
Entity bulletTest2 = createBullet(0,0); // recreate it, it doesn't work anymore
}
在下面的代码示例中,我创建了一个
BulletFactory
来创建由引擎制成的子弹实体。
public Entity createBullet(float x, float y) {
Entity entity = createEntity(Constants.Flags.BULLET);
BulletComponent bullet = engine.createComponent(BulletComponent.class);
SizeComponent size = engine.createComponent(SizeComponent.class);
TextureComponent texture = engine.createComponent(TextureComponent.class);
PhysicsComponent physics = engine.createComponent(PhysicsComponent.class);
TransformComponent transform = engine.createComponent(TransformComponent.class);
MovementComponent movement = engine.createComponent(MovementComponent.class);
texture.region = GameAssets.cannonball;
transform.position.set(x, y);
size.width = 0.25f;
size.height = 0.25f;
transform.origin.set(size.width / 2, size.height /2);
float bodyPosX = transform.position.x + transform.origin.x;
float bodyPosY = transform.position.y + transform.origin.y;
physics.body = createBulletBody(entity, bodyPosX, bodyPosY);
entity.add(bullet);
entity.add(size);
entity.add(texture);
entity.add(physics);
entity.add(transform);
entity.add(movement);
engine.addEntity(entity);
return entity;
}
public Entity createEntity(Constants.Flags flag) {
Entity e = engine.createEntity();
e.flags = flag.ordinal();
return e;
}