碰撞后如何使两个身体粘住?

时间:2014-01-22 21:02:11

标签: java libgdx box2d jbox2d

我真的坚持这个我可以成功地发现碰撞,但是我不能让两个身体参与碰撞而坚持下去。

这是我的 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());
        }
    };

这也是我在world.step()行

之后直接放在我的render()中的内容
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");
    }

我非常坚持在解决后解决或预先解决的问题真的很困惑。我跟着iforce2d粘性抛射物http://www.iforce2d.net/b2dtut/sticky-projectiles,但我不懂C ++,在eclipse中工作时会遇到很多语法错误。请有人给我看一个工作碰撞的示例代码,在java碰撞后,机体粘在一起。

1 个答案:

答案 0 :(得分:5)

这是使用libgdx包装器创建WeldJoint的方法:

WeldJointDef wd = new WeldJointDef();
wd.bodyA = body1;
wd.bodyB = body2;
wd.referenceAngle = wd.bodyB.getAngle() - wd.bodyA.getAngle();
world.createJoint( wd );

不要尝试在ContactListener中创建Joints。将要粘贴的实体添加到列表中,然后在 world.step 之后检查它们。

修改

好的,就像在iforce2d tutorial中一样,创建一个包含2个实体的对象:

public class StickyInfo{
    Body bodyA;
    Body bodyB;
    public StickyInfo(Body bodyA, Body bodyB){
        this.bodyA = bodyA;
        this.bodyB = bodyB;
    }
};

然后创建一个StickyInfo的libgdx Array

Array<StickyInfo> collisionsToMakeSticky = new Array<StickyInfo>();

当身体碰撞时(好吧,技术上是他们的固定装置),将它们添加到此列表中:

collisionsToMakeSticky.add(new StickyInfo(body1, body2))

然后在 world.step 之后,如果数组不为空。创建WeldJoints:

while(collisionsToMakeSticky.size>0){
    StickyInfo si = collisionsToMakeSticky.removeIndex(0);
    //Make the WeldJoint with the bodies si.bodyA and si.bodyB
}