How to check whether you have touched a body in Box2D iPhone?

By | August 24, 2012

You can check it by using the TestPoint function available for the Fixtures.

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
    for (b2Body *b = world->GetBodyList(); b; b = b->GetNext())
    {
 
        b2Fixture *f = b->GetFixtureList();
        CCSprite *sprite =(CCSprite *) b->GetUserData();
 
        if(sprite != NULL)
        { //Here there should be a userData (sprite) for this to work.
            if(f -> TestPoint(locationWorld))
            {
                NSLog(@"You touched a body");
                if (sprite.tag == 3)
                {
                //do something on touching a specific body.
                }
 
 
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *