简体   繁体   中英

Detect collision between two bodies in Box2d and libgdx(android)

I am new to libgdx and Box2d engine and I'm developing a game using same .I want to detect collision between two bodies to perform some function.But I'm not aware about the optimum way to do that and also want get point of collision.Kindly provide some suggestion with code.I have already implemented ContactListener but to no avail.

I'm using this code as a reference.

Thanks

You already did it the right way to create and set a ContactListener... (for a general setup, the libgdx wiki is great: https://github.com/libgdx/libgdx/wiki/box2d#contact-listeners )

If you now want to handle the specific contacts, you for exmaple need to add some implementation in the beginContact(); method of your listener. The beginContact(); method contains a Contact instance, which holds all you need:

  • FixtureA - the first fixture of a contact
  • FixtureB - the fixture, which FixtureA has collided with
  • WorldManifold - an object that holds the collision points etc

Through the fixtures you can access the bodies and the actors which you are drawing. The connection to your Actor can be done through the body.setUserData(actor); method.

Now you need to decide on how to find out the correct collisions. You can either work with sensors, which are box2d fixtures that just act as a sensor. That means that when an object collides with a sensor, it won't bounce, but fall through it instead. But you then are able to detect this contact within the listener.

Also, it might be a good idea to add some kind of GameObjectType to your actors. Imagine you create a jumping game where the player jumps from platform to platform with water below. Then you would create your actors with types like PLAYER, WATER, PLATFORM ... through the getUserData() method of the box2d bodies yu can now access the Actors and compare their types.

Eg when an Actor of type PLAYER collides with one of type WATER, he will drown...

Hope it helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM