LibGDX,移动物体时间歇性滞后

LibGDX, intermittent lagging whilst moving an object

我在我的屏幕顶部创建了小绵羊精灵,然后它们应该下降并在越过底线后消失。问题是,当他们穿过屏幕时,很明显有时他们会滞后。几毫秒,但可以看到它。它绝对随机发生。他们用 Gdx.graphics.getDeltaTime(); 改变他们的位置;

    public void update (float deltaTime) {
        updateMotionX(deltaTime);
        updateMotionY(deltaTime);

        // Move to new position
        position.x += velocity.x * deltaTime;
        position.y += velocity.y * deltaTime;
}

这是生成它们的代码:

    private Sheep spawnSheep(){
    Sheep sheep = new Sheep();
    sheep.dimension.set(dimension);

    // select random cloud image
    sheep.setRegion(regSheeps.random());

    // position
    Vector2 pos = new Vector2();

    pos.x = -0.19f; // position after end of level
    pos.y = 5;

    sheep.position.set(pos);

    //speed
    Vector2 speed = new Vector2();
    speed.y = 3.5f;
    sheep.terminalVelocity.set(speed);
    speed.y *= -1;
    sheep.velocity.set(speed);
    return sheep;

}

也许有人已经遇到过这个问题,我不知道为什么会这样,

滞后很可能是由垃圾收集引起的,因为您在游戏循环中不断分配内存。

您希望尽可能避免在游戏循环中调用 new,如果调用 new,您希望尽可能重用这些对象。

查看 libgdx 中的游泳池 http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/Pool.html

如果您return从一个方法中创建一个对象,例如 Vector2,则创建一个静态实例并将该对象重新用于 return 值。请注意,这不是线程安全的,再次调用该方法将覆盖第一次调用的值。

如果我是你,我会在你的代码中搜索单词 'new' 的任何实例,并确保其中的 none 在游戏循环中被频繁调用。您还希望了解将创建对象实例的调用方法。将整数转换为字符串等简单操作会浪费内存,创建数组副本等更明显的操作也会浪费内存。

您应该会发现这对跟踪内存分配很有用。 https://visualvm.java.net/