How to make a box2d Body object collidable with the other Body

不想你离开。 提交于 2019-12-11 16:17:18

问题


How to make a com.badlogic.gdx.physics.box2d.Body object collidable with the other Body in Scene2d(libgdx) while working with the Box2d extension, when both the body types are Dynamic.?


回答1:


if I understand correctly, your question can this helps

where to create the Body2, add this example in your code:

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

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

where to create the Body1, add this example in your code:

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

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

Now you have to use a contactlistener, this is an example,

 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");
            }

        }
}

where to create the World, add this example in your code:

.//

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

YourWorld.setContactListener(new CrearContactListener());

you can look http://box2d.org/manual.pdf, and read about preSolve and more ect



来源:https://stackoverflow.com/questions/27388199/how-to-make-a-box2d-body-object-collidable-with-the-other-body

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