Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JBox2D - Find collision coordinates

I'm writing a program in Java using JBox2D. I need to find the exact point of collision between two textures, if and when they collide.

I have the code to determine if a collision happens, and can obviously just call the collision object ID to determine which textures are colliding.

What I can't seem to figure out is how to grab the actual coordinates of the collision itself. I read the documentation, but it is very complicated and does not address this issue directly.

Here's my code:

import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.callbacks.ContactListener;
import org.jbox2d.collision.Manifold;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.dynamics.contacts.Contact;


public class MyContactListener implements ContactListener{


    //When they start to collide
    public void beginContact(Contact c) {

    System.out.println("CONTACT");

    Fixture fa = c.getFixtureA();
    Fixture fb = c.getFixtureB();

    Vec2 posA = fa.getBody().getPosition();
    Vec2 posB = fb.getBody().getPosition();



}

public void endContact(Contact c) {

}

public void preSolve(Contact c, Manifold m) {}

public void postSolve(Contact c, ContactImpulse ci){}

}
like image 386
bigcodeszzer Avatar asked Aug 11 '15 00:08

bigcodeszzer


1 Answers

To know where the collision happened, you should know that sometimes there is not only one point of collision, but a set of points.

extracted from manual

(Image extracted from this manual)

As the above manual says:

Box2D has functions to compute contact points for overlapping shapes. [...] These points [...] groups them into a manifold structure. [...]

Normally you don't need to compute contact manifolds directly, however you will likely use the result produced in the simulation.[...] If you need this data, it is usually best to use the WorldManifold structure [...].

You can access it inside the Contact c class:

public void beginContact(Contact c) {
    System.out.println("CONTACT");
    
    WorldManifold worldmanifold;
    worldmanifold = c.getWorldManifold();
    
    for(Vec2 point : worldmanifold.points){
        System.out.println("Contact at : [" + point.x + ", " + point.y "]");
    }
}

Important: I have never used this library (JBox2D), however, I'm familiar with it (since libGDX apparently use a similar one (Box2D)). Also, I don't know if JBox2D is Box2D (the C++ one) for Java, and if JBox2D and Box2D (the libGDX one) are related at all. So maybe some methods can change (point.x could be point.getX()).

You could check this site too, but this is for C++ (I use their answer to answer you).

like image 62
Alex Sifuentes Avatar answered Oct 13 '22 00:10

Alex Sifuentes