如何使box2d Body对象可与其他Body进行冲突

时间:2014-12-09 20:28:13

标签: libgdx box2d scene2d

如果两种体型都是动态的,当使用Box2d扩展时,如何使com.badlogic.gdx.physics.box2d.Body对象与Scene2d(libgdx)中的其他Body可以匹配。?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你的问题可以帮助

在哪里创建Body2,在代码中添加此示例:

.//
YourBody2 = YourWorld.createBody(bd);

YourBody2.createFixture(fixDef).setUserData("YourBody2");

在哪里创建Body1,在代码中添加此示例:

.//
YourBody1 = YourWorld.createBody(bd);

YourBody1.createFixture(fixDef).setUserData("YourBody1");

现在你必须使用一个contactlistener,这是一个例子,

 private class CrearContactListener implements ContactListener {

        public CrearContactListener(){

        }
        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
            // TODO Auto-generated method stub

        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
            // TODO Auto-generated method stub

        }

        @Override
        public void endContact(Contact contact) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beginContact(Contact contact) {
            // TODO Auto-generated method stub

            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();

            if(fixtureA.getUserData() != null && fixtureA.getUserData().equals("YourBody1") 
               && fixtureB.getUserData() != null && fixtureB.getUserData().equals("YourBody2")){

                Gdx.app.log("Contact","1");
            }

            if(fixtureB.getUserData() != null && fixtureB.getUserData().equals("YourBody1")
                && fixtureA.getUserData() != null && fixtureA.getUserData().equals("YourBody2")){

                Gdx.app.log("Contact","2");
            }

        }
}

在哪里创建World,在代码中添加此示例:

.//

YourWorld = new World(..., ....);

YourWorld.setContactListener(new CrearContactListener());

你可以查看http://box2d.org/manual.pdf,并阅读有关preSolve和更多内容的信息