Handling collisions/contacts between bodies etc:
This really important aspect, mostly of the every physics based game, to handle collisions/contacts between bodies, we will use ContactListener. Let's say we want to execute action after contact between body A and body B, with ContactListener, its really easy.
First step, create new contact listener:
private ContactListener createContactListener() { ContactListener contactListener = new ContactListener() { @Override public void beginContact(Contact contact) { final Fixture x1 = contact.getFixtureA(); final Fixture x2 = contact.getFixtureB(); } @Override public void endContact(Contact contact) { } @Override public void preSolve(Contact contact, Manifold oldManifold) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { } }; return contactListener; }
As you can see, it has two most important things, beginContact and endContact. We also created two objects in beginContact, as a reference to the bodies where contact occur.
- Step two, register your contact listener to your PhysicsWorld.
mPhysicsWorld.setContactListener(createContactListener());
As mentioned in my previous article - CREATING BODIES - you can 'set identifier' to your body, by setting user data, then you can compare user data inside contact listener, and execute actions if you are too lazy to check previous article, you can set user data to the body, this way:
yourBody.setUserData("player");
Now we can create check inside beginContact, to execute action when contact between body A with user data "player" and body with user data "monster" will occur.
if (x2.getBody().getUserData().equals("player")&&x1.getBody().getUserData().equals("monster")) { Log.i("CONTACT", "BETWEEN PLAYER AND MONSTER!"); }
That's all, with this simple and easy way, you may check when contact between different kind of bodies will occur, and execute your actions. Important notice: In example below, we are checking only once, and in this case we assume that x2 fixture will be our player and x1 fixture will be our monster body. It might be different (conversely) That's why sometimes you should include second check, with the same actions but with different order (x2 and x1)
HTML Comment Box is loading comments...