Header Ads

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

http://www.cocos2d-x.org/wiki/Box2D

http://build-failed.blogspot.pt/2012/08/freehand-drawing-with-cocos2d-x-and.html

http://www.cocos2d-x.org/forums/6/topics/52726?r=52788

https://code.google.com/p/cocos2d-x-projects/downloads/detail?name=Assignment02%20Final.zip&can=2&q=#makechanges

http://bold-it.com/cocos2d/cocos2d-x-box2d-tutorial-arctic-fling-game-modevtablet/

http://paralaxer.com/box2d-physics/

http://www.raywenderlich.com/28602/intro-to-box2d-with-cocos2d-2-x-tutorial-bouncing-balls

http://www.raywenderlich.com/28606/how-to-create-a-breakout-game-with-box2d-and-cocos2d-2-x-tutorial-part-2



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() };
    _contacts.push_back(myContact);
}
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()) 
    {
        _contacts.erase(pos);
    }
}
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()) {
              toDestroy.push_back(bodyB);
      }
}
// Sprite B = block, Sprite A = ball
else if (spriteA->getTag() == 2 && spriteB->getTag() == 1) {
            if (std::find(toDestroy.begin(), toDestroy.end(), bodyA) 
            == toDestroy.end()) {
            toDestroy.push_back(bodyA);
       }
}        
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!

No comments:

Powered by Blogger.