简体   繁体   中英

Why does my libgdx game progressively slow down?

I have a game that generates bodies forever until the game ends. For some reason, the game will be nice and smooth at first, but then it will start to slow down and become choppy as you keep going while playing. Then, after you die and restart, the game repeats this process. I dispose all I can. Here is what pushes the player body:

//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);

Sadly the best way to avoid this kind of memory leak is to track the objects yourself.

I've gotten around this problem by creating an array called bodies that holds all the bodies. Then you run a for loop something like this (sorry, JavaScript:)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM