I'm working on my first game using libgdx with box2d. I'm using the debug renderer to test my objects. I created some car like objects. Each car has a main body, which is a large polygon of 6 points (about 1 meter long, 0.7 meters high), and has 2 wheels attached by revolute joints.
The main car has a cannon and a machine gun attached, also via revolute joints.
The problem I'm facing is that the large part of the car is not doing collision as intended. When 2 cars hit each other, they are overlapping, like this:
Some notes:
Here's the code I'm using to create the bodies:
protected Body createBody(Material material, Shape shape, BodyType type, WorldWrapper world)
{
BodyDef bodyDef = new BodyDef();
bodyDef.type = type;
bodyDef.position.set(initialPosition);
Body body = world.createBody(bodyDef);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = this.material.getDensity();
fixtureDef.friction = this.material.getFriction();
fixtureDef.restitution = this.material.getRestitution();
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
return body;
}
The car goes forward using motors on the wheels revolute joints, built like this:
public void goForward()
{
for (RevoluteJoint joint : wheelJoints)
{
joint.enableMotor(true);
joint.setMotorSpeed(-this.engineSpeed);
joint.setMaxMotorTorque(this.engineTorque);
}
}
I'm using the following values:
Density = 2500;
Restitution = 0;
Friction = 0.1;
BodyType = Dynamic;
I'm using a 1/60 seconds world step, with velocityIterations = 6 and positionIterations = 2
Any idea what on what I'm missing here?
The main body of your car (the polygon) is concave. Box2D has trouble with concave polygons or if the vertices are in clockwise order. Try building those cars with two rectangles instead, that should work.
Btw: You seem to use an older version of libgdx. The current libgdx nightlies have an additional algorithm in the polygon.set function, which automaticly calculates the convex hull in counterclockwise order of the given vertices. So using that version should also fix your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With