Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collision in Libgdx box2D failing for some bodies

Tags:

libgdx

box2d

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:

Bodies colliding

Some notes:

  1. The wheels and cannons (smaller shapes) are doing collision fine. When the wheels touch the bodies are stopping
  2. If I detect collision via code, the collision is actually happening
  3. I tried this with a smaller object (a bullet fired from the machine gun), and I set the object's "isBullet" property to true as I saw in a different post (not proper collision in box2d), but had the same result (The bullet is circled in red):

Bullet object colliding

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?

like image 790
Charbel Avatar asked May 23 '13 18:05

Charbel


1 Answers

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.

like image 138
Shinni Avatar answered Oct 06 '22 06:10

Shinni