4

我真的坚持这一点,我可以成功检测到碰撞,但我不能让参与碰撞的两个物体粘在一起。

这是我的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中碰撞后身体粘在一起。

4

1 回答 1

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 中创建关节。将要粘合的物体添加到列表中,并在world.step之后检查它们。

编辑:

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

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

然后创建一个StickyInfo的libgdx 数组

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

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

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

然后在world.step之后,如果 Array 不为空。创建焊接接头:

while(collisionsToMakeSticky.size>0){
    StickyInfo si = collisionsToMakeSticky.removeIndex(0);
    //Make the WeldJoint with the bodies si.bodyA and si.bodyB
}
于 2014-01-22T21:39:26.067 回答