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){
    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);
    // add the fixture definitions to the body
    sc->addFixturesToBody(body, "d_stand_1_scaled");

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