2
votes

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)

1

1 Answers

1
votes

The best course of action in this situation is to focus on the game logic first and use design pattern conventions over optimization techniques. Once you are happy with what the game does you can use profiling tools to determine how well the game does what it does. libGDX seems to have its own set of tools. As regards BodyDef objects, the construction is extremely simple. It's just a bunch of primitives being set to their defaults. Memorywise, about 9 (floats)*4 + (booleans, considering each boolean in JVM is maximum a byte)5 + 5 (references) * ~8 (on 64bit) = roughly 81 bytes, give or take, per BodyDef object. Source of BodyDef here. So shouldn't be a problem at all. If you limit the scope of your definition objects, then on body destruction there shouldn't be any references tracing back to definitions, so they will be marked for cleanup automatically.

Regarding ECS, I don't see how that fits in the question. Here's info about ECS and libGDX ECS.