[Cocos 2d-x v3.0] Box2D and Collisions

Public on June 6, 2014








To find out when a fixture collides with another fixture in Box2D, we need to register a contact listener. A contact listener is a C++ object that we give Box2D, and it will call methods on that object to let us know when two objects begin to touch and stop touching. we can’t just store references to the contact points that are sent to the listener, because they are reused by Box2D. So we have to store copies of them instead.
void MyContactListener::BeginContact(b2Contact* contact) 
    // We need to copy out the data because the b2Contact passed in
    // is reused.
    MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB() };
The following iterates through all of the buffered contact points, and checks to see if any of them are a match between the ball and the bottom of the screen.
void MyContactListener::EndContact(b2Contact* contact) 
    MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB() };
    std::vector::iterator pos;
    pos = std::find(_contacts.begin(), _contacts.end(), myContact);
    if (pos != _contacts.end()) 
In the Helloworld.cpp,“tick” method wil use _contactListener to go through the contact points of bodies that are colliding. If a sprite is intersecting with a block, we add the block to a list of objects to destroy.
b2Body *bodyA = contact.fixtureA->GetBody();
b2Body *bodyB = contact.fixtureB->GetBody();
if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();

// Sprite A = ball, Sprite B = Block
if (spriteA->getTag() == 1 && spriteB->getTag() == 2) {
    if (std::find(toDestroy.begin(), toDestroy.end(), bodyB) 
             == toDestroy.end()) {
// Sprite B = block, Sprite A = ball
else if (spriteA->getTag() == 2 && spriteB->getTag() == 1) {
            if (std::find(toDestroy.begin(), toDestroy.end(), bodyA) 
            == toDestroy.end()) {
Now you have even more techniques to add to Box2D in your game. I look forward to seeing some cool physics games from you guys!

[Advertising]Faster Thinking - Speed up your brain

Faster Thinking Game

sentiment_satisfied Emoticon