I'm working in a game in which I spawn an object every 1-3 seconds. This game object contains some assets for renderization purposes and a Box2D body. The thing is that I don't want to create thousands of objects. Instead, I would like to reuse them, resetting its properties (position, friction, etc.) and not creating a brand new object. I think that the best way to do this is implementing a pool of this objects but I'm concerned about it because after search for some info I've found several developers reporting memory leaks because all the objects created by Box2D internally.
What do you think is the best way to do this?
This is the class that I use to represent each game object:
public class GameObject extends Box2dGameObject {
private static final float WIDTH = 0.85f;
private static final float HEIGHT = 1;
private Animation animationDying;
private Animation animationFalling;
private Animation animationIdle;
private Animation animationJumping;
private Animation animationRunning;
private Body body;
public GameObject(Vector2 position, World world) {
super(position, world);
init();
}
private void init() {
super.init();
dimensions.set(WIDTH, HEIGHT);
/* Get assets */
animationDying = Assets.instance.pirate.animationDying;
animationFalling = Assets.instance.pirate.animationFalling;
animationIdle = Assets.instance.pirate.animationIdle;
animationJumping = Assets.instance.pirate.animationJumping;
animationRunning = Assets.instance.pirate.animationRunning;
/* Set default animation */
setAnimation(animationIdle);
body = createBox2dBody();
}
private Body createBox2dBody() {
BodyDef bodyDef = new BodyDef();
bodyDef.fixedRotation = true;
bodyDef.position.set(position);
bodyDef.type = BodyType.DynamicBody;
PolygonShape shape = new PolygonShape();
shape.setAsBox(WIDTH / 2, HEIGHT / 2);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 1;
fixtureDef.friction = 1;
fixtureDef.shape = shape;
Body body = world.createBody(bodyDef);
fixture = body.createFixture(fixtureDef);
shape.dispose();
return body;
}
/* More code omitted */
}