Shrinking box2d objects

Assumptions are that you are familiar around the concept of box2d and creating vertex around the textures in order to create collisions etc. There are many ways to do this but for me the following worked perfectly using cocos2d-x framework For this Textures of two different sizes are required.

What the Hell?!

I have used Physics editor to create vertex around the textures. In short this is how it works

  • Textures of two different sizes
  • Create exactly same vertex around each of the textures
  • When scaling down, destroy the body and recreate it with the smaller body
  • When scaling up, destroy the body and recreate it with the bigger body

Following code will shrink the box2d body:


void Layer::shrinkFixture(Sprite *devil, b2World* world, b2Body* body){
    
    world->DestroyBody(body);
    body->SetUserData(NULL);
    body = null;
    
    GB2ShapeCache* sc = GB2ShapeCache::getInstance();
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(devil->getPositionX()/ptmRatio, devil->getPositionY()/ptmRatio);
    bodyDef.userData = devil;
    body = world->CreateBody(&bodyDef);
    body->SetFixedRotation(true);
    body->SetBullet(true)
    
    // add the fixture definitions to the body
    sc->addFixturesToBody(body, "d_stand_1_scaled");
    devil->setAnchorPoint(sc->anchorPointForShape("d_stand_1_scaled"));
    body->ResetMassData();
}


The code for GB2ShapeCache can be found HERE. Below is a sample video to show how all this adds up.

Posted in Tutorials Tagged with: ,

Leave a Reply

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

*

Join 1 other subscriber