3
votes

I'm trying to create a game with "libGDX" and "Box2D". I've several shapes in the game, so I created a BodyFactory class which creates my bodies using PolygonShape

The problem is, when I create a body, with Shape.setAsBox() method, everything works fine, but when I create bodies with PolygonShape.set(vertices), the position of bodies changes as I wish, but they won't rotate at all.

This is what I get (after stability) when I drop 3 bodies from the sky:

enter image description here The square rotates and stays at the ground, bot the other shapes won't.

Also note that I tried adding

body.setFixedRotation(false);

to my code, but nothing changed.

Also friction, mass and density of shapes are at a reasonable amount.

This is the part of my code which creates a "PolygonShape" from a file:

...
Body body = world.createBody(bodyDef);
...
for (int i = 0; i < bodyConf.meshData.length; i++) {
    PolygonShape polygonShape = new PolygonShape();
    polygonShape.set(bodyConf.meshData[i]);
    fixtureDef.shape = polygonShape;
    body.createFixture(fixtureDef);
    polygonShape.dispose();
}
1

1 Answers

2
votes

I think the problem is that you are creating only one Body with three Fixtures attached to it.

What you actually want is three Bodys, with one Fixture attached to each of them. That way, each body can rotate independent from the others.

for (int i = 0; i < bodyConf.meshData.length; i++) {
    BodyDef bodyDef = ...;
    Body body = world.createBody(bodyDef);
    PolygonShape polygonShape = new PolygonShape();
    polygonShape.set(bodyConf.meshData[i]);
    fixtureDef.shape = polygonShape;
    body.createFixture(fixtureDef);
    polygonShape.dispose();
}