使用 libgdx 的 PolygonRegion/PolygonSprite 时出现奇怪、不一致和故障的结果

Weird, inconsistent and glitchy results when using libgdx's PolygonRegion/PolygonSprite

我在 libgdx 和 box2d 中构建了一个可破坏的地形,现在我想从纹理渲染剩余的(未破坏的)地形。每次 box2d 物体受到 "explosion" 影响(地形的一部分被移除)时,物体被移除并用新的多边形重新制作。我认为 libgdx 的 PolygonSprite 非常适合这项任务,但我一直遇到问题。

在这个例子中,我在地形中创建了一个 "U" 圆形 "explosions"。

此代码运行良好:

protected Body createBody(Polygon inputPolygon) {
        ...
        body.setUserData(inputPolygon.getVertices());
        ...
}
//Later in the render method
        sr.setProjectionMatrix(cameraMatrix); //ShapeRenderer sr = new ShapeRenderer();
        sr.begin(ShapeRenderer.ShapeType.Line);
        Array<Body> bodies = new Array<Body>();
        world.getBodies(bodies);
        sr.setColor(Color.BLACK);
        for (Body b : bodies) {
        sr.polygon((float[]) b.getUserData());
        }
        sr.end();

并生成如下内容:

当我尝试通过 PolygonSprites(或 PolygonRegions)渲染带有纹理的 "terrain" 时,如下所示:

protected Body createBody(Polygon inputPolygon) {
        ...
        //triangulator is a EarClippingTriangulator
        ShortArray indices = triangulator.computeTriangles(inputPolygon.getVertices());
        //The TextureRegion is 100x40 px and the inputPolygon represents a part of this texture (the vertices/coordinates are
        //in the same scale, so an inputPolygon with the vertices (0, 0  100, 0  100, 40,  0, 40) would represent the whole TextureRegion.
        PolygonSprite polygonSprite = new PolygonSprite(new PolygonRegion(terrainTexture, inputPolygon.getVertices(), indices.items));
        polygonSprite.setOrigin(0, 0);
        body.setUserData(polygonSprite);
        ...
}
//Later in the render method
        Array<Body> bodies = new Array<Body>();
        world.getBodies(bodies);
        for (Body b : bodies) {
        //Yes the screen is cleared correctly before, the batch is a
        //PolygonSpriteBatch, the batch is started with begin() and end()
        //and the projection matrix is set correctly.
            ((PolygonSprite) b.getUserData()).draw(batch);
        }

我最终得到了这样的奇怪、不一致和故障的结果: ...或者像这样:

地形(纹理)是这样开始的:

EarClippingTriangulator.computeTriangles() 的 JavaDoc 说:

Note the returned array is reused for later calls to the same method.

因此您可能希望在将索引传递给 PolygonRegion 之前复制它们。