I'm trying to make a concave polygon body in JBox2D by combining convex polygons. This is what I've tried:
Vec2[][] v = { { new Vec2(-3.5f, 0), new Vec2(-3.5f, 0.5f), new Vec2(3.5f, 0.5f), new Vec2(3.5f, 0) },
{ new Vec2(-3.5f, 0.5f), new Vec2(-3.5f, 3), new Vec2(-3, 3), new Vec2(-3, 0.5f) },
{ new Vec2(3.5f, 0.5f), new Vec2(3.5f, 3), new Vec2(3, 3), new Vec2(3, 0.5f) } };
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(x, y);
bodyDef.type = BodyType.DYNAMIC;
Body body = WORLD.createBody(bodyDef);
for (int i = 0; i < v.length; i++) {
PolygonShape polygonShape = new PolygonShape();
polygonShape.set(v[i], v[i].length);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 0.1f;
fixtureDef.shape = polygonShape;
body.createFixture(fixtureDef);
}
But this doesn't work well. It produces messed up shapes and the body freezes upon contact with other bodies. After some bug testing I found out that it's because of the vertices messing up. I added this code to the end:
for (Fixture f = body.getFixtureList(); f != null; f = f.getNext()) {
Vec2[] v = ((PolygonShape) f.getShape()).getVertices();
for (int i = 0; i < v.length; i++) {
System.out.println(v[i].x + " " + v[i].y);
}
System.out.println();
}
And it gave me this:
3.5 0.5
3.5 3.0
3.0 3.0
3.0 0.5
0.0 0.0
0.0 0.0
0.0 0.0
0.0 0.0
-3.5 0.5
-3.5 3.0
-3.0 3.0
-3.0 0.5
0.0 0.0
0.0 0.0
0.0 0.0
0.0 0.0
-3.5 0.0
-3.5 0.5
3.5 0.5
3.5 0.0
0.0 0.0
0.0 0.0
0.0 0.0
0.0 0.0
Which is right, except it also produces four extra vertices at (0.0, 0.0) for each fixture. This causes the polygons to become concave which is not good. I naturally started testing and found that this shape worked just fine and didn't produce those extra vertices:
float sqrt2 = (float) Math.sqrt(2);
Vec2[][] v = { { new Vec2(2, 0), new Vec2(sqrt2, sqrt2), new Vec2(0, 2), new Vec2(-sqrt2, sqrt2),
new Vec2(-2, 0), new Vec2(-sqrt2, -sqrt2), new Vec2(0, -2), new Vec2(sqrt2, -sqrt2) } };
So I thought that it has something to do with having multiple fixtures, but I then found out that this doesn't work (produces those four additional vertices at 0,0):
Vec2[][] v = { { new Vec2(2, 2), new Vec2(2, -2), new Vec2(-2, -2), new Vec2(-2, 2) } };
Which makes me all confused again! If those additional four vertices wouldn't show up then everything would've worked fine, so what am I doing wrong?
I'm somewhat new to Box2D, so keep that in mind.