How to make a box2d Body object collidable with th

2019-08-29 00:59发布

问题:

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