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 Locations
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];

//Converting to cocos2D positioning
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

     //Getting body list from world
     for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) {
          //Getting Fixture from the bodies
          b2Fixture *bf1 = b->GetFixtureList();
          //Checking whether the fixture contains touch location!
          if (bf1->TestPoint(locationWorld)) {
             //If YES assigning user data to a sprite tempSprite
             CCSprite *tempSprite = (CCSprite *) b->GetUserData();
             //Checking whether the user data sprite tag is 7
             if (tempSprite .tag==7) {
                //If YES then remove the sprite & the body!
                [self removeChild:tempSprite cleanup:YES];

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


Leave a Reply

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




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.