javascriptbox2dcollisionbox2dweb

Box2dWeb call function when objects collide


I'm fairly new to javascript and box2d, i was wondering if someone knows how i can call a custom function when two objects collide. I tried using some examples that uses the b2ContactListener without any succes. I've placed an object above another and let the standard Box2d physics do it's thing.

I recieve two console outputs, the first is null and the second is Ball with the following code:

var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function(contact) {
    console.log(contact.GetFixtureA().GetBody().GetUserData()); 
    console.log(contact.GetFixtureB().GetBody().GetUserData());
};. 

The two objects that need to collide are a b2_dynamicbody (ball) and a b2PolygonShape. (rectangle). Using bodyDef.userData = "Ball"; in my Ball.js and bodyDef.userData = "Mouse"; in my Mouse.js i try to identify if they are hit. Instead only the ball is displayed.

Next to that i'm sure this is not the correct way for detecting collision :P I hope i've explained it well enough, could somebody steer me in the right direction?


Solution

  • Ok I solved it myself, apparently I had to add my custom event to the world I create with box2d. So, the issue was solved by me reading big chunks of box2d documentation/manual which can be found here:

    I started with adding a String as UserData() to every object which can collide and has to do something else next to just colliding. Using the following code:

    bodyDef.userData = "Car";
    

    note: every object has to have it's own unique string.

    Then I created a new contact listener (formulated in my question above) and listened for fixtures colliding with each other. When that happens, I 'save' the fixtures UserData() in variables which I can then use to look what objects collide with each other.

    var contactListener = new Box2D.Dynamics.b2ContactListener;
    contactListener.BeginContact = function(contact) {
    
        var fixA = contact.GetFixtureA().GetBody().GetUserData();
        var fixB = contact.GetFixtureB().GetBody().GetUserData();
    
        // if else statement here...
    
    };
    
    world.SetContactListener(contactListener);
    

    Finally, I added the last statement world.SetContactListener(contactListener); to add the event to the world, making it possible for it to listen to collisions, which I forgot to add and thus was my problem.

    Hope someone finds this usefull!