Curnelious
Curnelious

Reputation: 1

How to know which body collide?

i am using cocos2d and box2d, with contact listener, and lets say i have a body that can hit a number of other bodies, BUT each one of them is turn on the contact listener. so how can i know who hit who ?

i have this in my tick :

for(pos = _contactListener->_contacts.begin(); pos != _contactListener->_contacts.end(); ++pos) 
{
    MyContact contact = *pos;
    b2Body *bodyA=contact.fixtureA->GetBody();
    b2Body *bodyB=contact.fixtureB->GetBody();

    //check if collision between to bodies
    if( bodyA->GetUserData() !=NULL && bodyB->GetUserData() !=NULL)    //if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||(contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture))
    {
        NSLog(@"Ball hit bottom!");
    }

thanks a lot .

Upvotes: 2

Views: 270

Answers (2)

while creating the body set userdata like this

CCSprite *red=[CCSprite spriteWithFile:@"red.png"];

red.tag=3;

[self addChild:red];

b2BodyDef bd;

bd.type=b2_dynamicBody;

bd.position.Set(w/PTM_RATIO,h/PTM_RATIO);   

bd.userData=red;


for(pos = _contactListener->_contacts.begin(); pos != _contactListener->_contacts.end(); ++pos) 
{
    MyContact contact = *pos;
    b2Body *bodyA=contact.fixtureA->GetBody();
    b2Body *bodyB=contact.fixtureB->GetBody();

    //check if collision between to bodies
    if( bodyA->GetUserData() !=NULL && bodyB->GetUserData() !=NULL)    //if ((contact.fixtureA == _bottomFixture && contact.fixtureB == _ballFixture) ||(contact.fixtureA == _ballFixture && contact.fixtureB == _bottomFixture))
    {
        so here 


       CCSprite *actor = (CCSprite*)bodyA->GetUserData();


        if ([actor tag] == 3) {
             //red box

        }


    }

Upvotes: 2

Andrew
Andrew

Reputation: 24866

Put some identifier into user data. For example:

struct MyUserData
{
    int myUniqueId;
};

When creating bodies attach some unique number to each and then you will be able to understand which body was colliding.

Upvotes: 1

Related Questions