CoderzHeaven

April 10, 2011

How to remove box2D body from world ?

Hi,
If you are a game developer and you are using box2D for real world simulations, you would probably need a particular body to be removed from the box2D world! But how can you remove box2D body from world ? See the following sample code which does the same.

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{//Getting Touch LocationsUITouch *touch = [touches anyObject];CGPoint location = [touch locationInView: [touch view]];location = [[CCDirector sharedDirector] convertToGL: location];//Converting to cocos2D positioningb2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);//Getting body list from worldfor (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) {//Getting Fixture from the bodiesb2Fixture *bf1 = b->GetFixtureList();//Checking whether the fixture contains touch location!if (bf1->TestPoint(locationWorld)) {//If YES assigning user data to a sprite tempSpriteCCSprite *tempSprite = (CCSprite *) b->GetUserData();//Checking whether the user data sprite tag is 7if (tempSprite .tag==7) {//If YES then remove the sprite & the body![self removeChild:tempSprite cleanup:YES];world->DestroyBody(b);}}}}

Here tag 7 is what we previously assigned for the sprite corresponding to the body’s user data!

Leave a Reply Cancel reply