三角测量搞乱三角形

时间:2015-02-04 09:45:04

标签: libgdx box2d polygon triangulation

我正在尝试对凸多边形进行三角测量。

screenshot

左边是三角形多边形,右边是没有三角剖分的凸多边形。 (两者都错了)但是右边的那个是正确的位置,除了它缺少凸起的部分之外,它还可以......

我创建三角形并将它们添加到arraylist

    float[] vertices = polygonObject.getPolygon().getTransformedVertices();
    float[] worldVertices = new float[vertices.length];

    for (int i = 0; i < vertices.length; ++i) {
        System.out.println(vertices[i]);
        worldVertices[i] = vertices[i] / ppt;
    }

    // Make triangles
    Vector<float[]> trianglesVertices = new Vector<float[]>();

    EarClippingTriangulator triangulator = new EarClippingTriangulator();
    ArrayList<PolygonShape> triangles = new ArrayList<PolygonShape>();

    ShortArray pointsCoords = triangulator.computeTriangles(worldVertices);

    for (int i = 0; i < pointsCoords.size / 6; i++)
    {
        trianglesVertices.add(new float[] {
                pointsCoords.get(i*6),      pointsCoords.get(i*6 + 1),
                pointsCoords.get(i*6 + 2),  pointsCoords.get(i*6 + 3),
                pointsCoords.get(i*6 + 4),  pointsCoords.get(i*6 + 5),
        });

        PolygonShape triangleShape = new PolygonShape();
        triangleShape.set(trianglesVertices.get(i));
        triangles.add(triangleShape);
    }

后来我循环了那个arraylist并创建了一些实体,但不知怎的,libgdx(可能是我,而不是libgdx)完全混淆了它。

            for(PolygonShape triangle:triangles){
                BodyDef bd = new BodyDef();
                bd.type = BodyDef.BodyType.StaticBody;
                Body body = world.createBody(bd);
                body.createFixture(triangle, 1);

                bodies.add(body);

                triangle.dispose();
            }

这是我试图在libgdx中渲染的形状(在Tiled中创建) correct shape

1 个答案:

答案 0 :(得分:0)

我找到了另一个例子,它有效!

https://github.com/MobiDevelop/maps-editor/blob/master/maps-basic/src/com/mobidevelop/maps/basic/BasicMapRenderer.java#L151

我从这个数组创建三角形的方式是错误的

ShortArray pointsCoords = triangulator.computeTriangles(worldVertices);

这里是正确创建三角形的代码,

    for (int i = 0; i < pointsCoords.size; i += 3) {
        int v1 = pointsCoords.get(i) * 2;
        int v2 = pointsCoords.get(i + 1) * 2;
        int v3 = pointsCoords.get(i + 2) * 2;

        PolygonShape triangleShape = new PolygonShape();
        triangleShape.set(
                new float[]{
                        worldVertices[v1 + 0],
                        worldVertices[v1 + 1],
                        worldVertices[v2 + 0],
                        worldVertices[v2 + 1],
                        worldVertices[v3 + 0],
                        worldVertices[v3 + 1]
                }

        );
        triangles.add(triangleShape);
    }