How to make two bodies stick after a collision?

天大地大妈咪最大 提交于 2019-12-05 13:49:33

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!