Box2dweb - Collision Contact Point

2019-03-27 03:46发布

问题:

I use box2dweb. I am trying to develop a game. At some point I need to find out the contact point between a "Circle" and "Box". All I know is it can be done using b2ContactListener. We can receive contact data by implementing b2ContactListener using Post-Solve Event. Please help!

回答1:

You are on the right track there are various events you can hook into with the b2ContactListener:

var b2Listener = Box2D.Dynamics.b2ContactListener;

//Add listeners for contact
var listener = new b2Listener;

listener.BeginContact = function(contact) {
    //console.log(contact.GetFixtureA().GetBody().GetUserData());
}

listener.EndContact = function(contact) {
    // console.log(contact.GetFixtureA().GetBody().GetUserData());
}

listener.PostSolve = function(contact, impulse) {
    if (contact.GetFixtureA().GetBody().GetUserData() == 'ball' || contact.GetFixtureB().GetBody().GetUserData() == 'ball') {
        var impulse = impulse.normalImpulses[0];
        if (impulse < 0.2) return; //threshold ignore small impacts
        world.ball.impulse = impulse > 0.6 ? 0.5 : impulse;
        console.log(world.ball.impulse);
    }
}

listener.PreSolve = function(contact, oldManifold) {
    // PreSolve
}

this.world.SetContactListener(listener);

Just remove the postSolve code and depending on what you need to do hook into the appropriate events.

Seth ladd has some great articles on his blog about collision/reacting to them. This is where I picked up these bits so full credit goes to him.

I hope this helps.

Thanks, Gary