我在一个游戏中工作,我每 1-3 秒生成一个对象。该游戏对象包含一些用于渲染目的的资产和一个 Box2D 主体。问题是我不想创建数千个对象。相反,我想重用它们,重置它的属性(位置、摩擦力等),而不是创建一个全新的对象。我认为最好的方法是实现这些对象的池,但我很担心,因为在搜索了一些信息后,我发现有几个开发人员报告内存泄漏,因为所有对象都是由 Box2D 在内部创建的。
您认为最好的方法是什么?
这是我用来表示每个游戏对象的类:
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 */
}