Why there is a phantom contact points in my Box2d libgdx game

Viewed 81

I'am writing game using libgdx and box2d. When an object touches another, phantom contact points often occur. This is how i drawing contact points:

private void renderContactPoints() {
    for (Contact contact : world.getContactList())
        for (Vector2 point : contact.getWorldManifold().getPoints())
            renderer.getBatch().draw(tex, point.x * PPM, point.y * PPM, 20, 20);

}

Screenshot of problem

Screenshot of problem

1 Answers

For performance Box2D and libGDX re-uses arrays to avoid reallocation, therefore you cannot iterate the full result of getContactList and getPoints as you'll get too many results.

Instead, query the number of items first:

private void renderContactPoints() {
    for(int i = 0; i < world.getContactCount(); ++i) {
        Contact contact = world.getContactList().get(i);
        for (int j = 0; j < contact.getWorldManifold().getNumberOfContactPoints(); ++j) {
            Vector2 point = contact.getWorldManifold().getPoints()[j];
            renderer.getBatch().draw(tex, point.x * PPM, point.y * PPM, 20, 20);
        }
    }
}    
Related