Lately many people keep asking about how to make collision/contact check's between bodies, it was explained couple of times - more or less, I will create this brief guide, to keep most important informations about this subject in one thread. * If it there is already similar guide, please remove this one (sorry in advance)
Short description: as we know (or some of you don't) we can check collisions between shapes (for example sprites), with simple check:
Using java Syntax Highlighting
- if (x.collidesWith(y)
- {
- // action
- }
Parsed in 0.030 seconds, using GeSHi 1.0.8.4
But, its not enough for bodies, that's why we can use Contact Listener.
1. Creating new contact listener:
Using java Syntax Highlighting
- private ContactListener contactListener2()
- {
- ContactListener contactListener = new ContactListener()
- {
- @Override
- public void beginContact(Contact contact)
- {
- }
- @Override
- public void endContact(Contact contact)
- {
- }
- @Override
- public void preSolve(Contact contact, Manifold oldManifold)
- {
- }
- @Override
- public void postSolve(Contact contact, ContactImpulse impulse)
- {
- }
- };
- return contactListener;
- }
Parsed in 0.032 seconds, using GeSHi 1.0.8.4
There are implemented, two most important functions (beginContact and endContact)
Also we have to register this contact listener, to our physic world.
Using java Syntax Highlighting
- mPhysicsWorld.setContactListener(contactListener());
Parsed in 0.033 seconds, using GeSHi 1.0.8.4
Those give us possibilities to do certain actions, when there is contact between 2 bodies (or contact is ended)
Obviously, we have to 'receive' those 2 bodies somehow, to reference to them
Using java Syntax Highlighting
- Fixture x1 = contact.getFixtureA();
- Fixture x2 = contact.getFixtureB();
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
And now lets say we want to Log info while there is contact between two bodies, so we have to add this check in beginContact
Using java Syntax Highlighting
- if (x2.getUserData().equals("player") || x1.getUserData().equals("monster"))
- {
- Log.i("CONTACT", "BETWEEN PLAYER AND MONSTER!");
- }
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
as you most likely noticed, we used getUserData() function, to retrieve "data/reference name of the object/body/shape"
It means, you can use setUserData() function, to 'name' somehow your object.
For example:
Using java Syntax Highlighting
- Body b = PhysicsFactory.createBoxBody(mPhysicsWorld, testSprite, BodyType.KinematicBody, wallFixtureDef);
- b.setUserData("monster");
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
Then we can reference to those names, using contact listener (with way posted above)
Hopefully its easy to understand, thanks!
