问题
I am really stuck on this I can successfully detect a collision but I can't make the two bodies involved in the collision to stick.
Here is my ContactListener
world.setContactListener(listener);
listener = new ContactListener() {
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
//called when two fixtures cease to touch
@Override
public void endContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Gdx.app.log("beginContact", "between" + fixtureA.toString() + "and" + fixtureB.toString());
}
//called when two fixtures begin to touch
@Override
public void beginContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Gdx.app.log("beginContact", "between" + fixtureA.toString() + "and" + fixtureB.toString());
}
};
Also this is what I put in my render() straight after the world.step() line
int numContacts = world.getContactCount();
if(numContacts > 0)
{
Gdx.app.log("contact", "start of contact list");
for(Contact contact: world.getContactList())
{
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Gdx.app.log("contact", "between" + fixtureA.toString() + "and" + fixtureB.toString());
}
Gdx.app.log("contact", "end of contact list");
}
I am extremely stuck on what to put on post solve or pre-solve really confused. I followed the iforce2d sticky projectiles http://www.iforce2d.net/b2dtut/sticky-projectiles but I don't understand C++ and i get a lot of syntax errors when working in eclipse. Please can someone show me an example code of a working collision where bodies stick together after colliding in java please.
回答1:
This is how you create a WeldJoint with the libgdx wrapper:
WeldJointDef wd = new WeldJointDef();
wd.bodyA = body1;
wd.bodyB = body2;
wd.referenceAngle = wd.bodyB.getAngle() - wd.bodyA.getAngle();
world.createJoint( wd );
Do not try to create Joints inside the ContactListener. Add the bodies to be glued to a list and check them just after world.step.
EDIT:
Ok, like in the iforce2d tutorial,create an object to contain 2 bodies:
public class StickyInfo{
Body bodyA;
Body bodyB;
public StickyInfo(Body bodyA, Body bodyB){
this.bodyA = bodyA;
this.bodyB = bodyB;
}
};
Then create a libgdx Array of StickyInfo's
Array<StickyInfo> collisionsToMakeSticky = new Array<StickyInfo>();
When the bodies collide (well, technically their fixtures), add them to this list:
collisionsToMakeSticky.add(new StickyInfo(body1, body2))
And then just after world.step, if the Array is not empty. Create the WeldJoints:
while(collisionsToMakeSticky.size>0){
StickyInfo si = collisionsToMakeSticky.removeIndex(0);
//Make the WeldJoint with the bodies si.bodyA and si.bodyB
}
来源:https://stackoverflow.com/questions/21293923/how-to-make-two-bodies-stick-after-a-collision