开发者

How to know which body collide?

开发者 https://www.devze.com 2023-03-17 17:23 出处:网络
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.

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 .


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

        }


    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消