为什么我的libgdx游戏逐渐减慢?

时间:2014-03-16 06:34:22

标签: java android performance libgdx box2d

我有一个永远生成身体的游戏,直到比赛结束。出于某种原因,游戏一开始会很好而且流畅,但随着游戏的进行,它会开始变慢并变得不稳定。然后,在您死亡并重新启动后,游戏会重复此过程。我尽我所能。这是推动玩家身体的原因:

//in main game class
private Vector2 movement = new Vector2();
sSpeed = 200000;
switch(button)
{
        case Buttons.LEFT:
            movement.y = sSpeed * 1.2f;
            movement.x = sSpeed * 1.5f;
            table.clear();
        }
        return false;
}

//in Level Generator class
public LevelGenerator(BodyDef bDef, float topEdge, float bottomEdge, float minGap, float maxGap, float w, float h, Sprite s, World world) {
    this.bDef = bDef;
    this.topEdge = topEdge;
    this.bottomEdge = bottomEdge;
    this.minGap = minGap;
    this.maxGap = maxGap;
    width = w;
    height = h;
    this.s = s;
    this.world = world;
}

public void generate(float rightEdge) {
    if(x + MathUtils.random(minGap, maxGap) > rightEdge) {
        return;
    }
    x = rightEdge;
    float y = MathUtils.random(topEdge - height * 2f, bottomEdge + height * 2f);

    bDef = new BodyDef();
    bDef.type = BodyType.DynamicBody;

    PolygonShape ast = new PolygonShape();
    ast.setAsBox(width, height, new Vector2(x + width, y + height), 0);

    item = world.createBody(bDef);
    Fixture fix = item.createFixture(ast, 0);
}

//in main game class
generator.generate(camera.position.x + camera.viewportWidth / 2 + 10);
generator = new LevelGenerator(ballD3, 120, -125, 58, 63, 12.5f, 12.5f, aSprite1 , world);

1 个答案:

答案 0 :(得分:0)

可悲的是,避免此类内存泄漏的最佳方法是自己跟踪对象。

我通过创建一个包含所有实体的bodies数组来解决这个问题。然后你运行这样的for循环(抱歉,JavaScript:)

_.each(bodies,function(body){
  var pos = body.GetPosition();
  if (pos.y > 500) world.destroyBody(body);
});