Background
I am developing a game (using LibGDX) and have recently learned about Entity-Component Systems. I decided to use the ECS that came with LibGDX, Ashley. However, this probably applies to using Box2D with any Entity-Component System.
Problem
Creating a Box2D body and attaching a shape is relatively complex. Here is a basic example:
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(0, 0);
Body body = world.createBody(bodyDef);
CircleShape shape = new CircleShape();
shape.setRadius(1f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
shape.dispose();
BodyDefs and FixtureDefs are copied when Bodies and Fixtures are created from them, so they are reusable. Many of my game objects always have the same shape, so they can share a FixtureDef:
private static PolygonShape shape = new PolygonShape();
public static FixtureDef platformFixtureDef = new FixtureDef();
static {
shape.setAsBox(1f, 0.2f);
platformFixtureDef.shape = shape;
// as a side question, in this situation, how should I dispose of the shape when the game is over/closed?
}
However, while most parts of a BodyDef remain the same for any certain type of objects, the position is always different. How should I go about keeping most parts of a BodyDef the same, while just changing the position? Is it better to reuse one static BodyDef, changing the position variables each time?
Or is it better for each Body I want to create, to create a new BodyDef? If I create a new BodyDef each time, will this impact memory usage or performance? (I am creating ~10 per second)