How to load b2bodies from physics editor and remove the corresponding body with its sprite of an array on touch in cocos2dx | Techbirds

//ADD SPRITES TO THE SCENE
CCSprite *sprite1=CCSprite::create("sprite1.png");

//Let the scaling factor is rX and rY for X and Y direction

sprite1->setScaleX(rX); sprite1->setScaleY(rY);

scene->addChild(sprite1);

//Similarly we can add other sprites also which are to be in the array

//ADD ALL THESE SPRITES TO THE CCARRAY

CCArray *arr=new CCArray; arr->addObject(sprite1);

In above sprite declaration,position of the sprite is not defined as we will attach the corresponding b2body to the sprite later and the sprite will take the position of the body as its own through the update function.

//HOW TO LOAD THE BODIES TRACED IN PHYSICS EDITOR TO THE CORRESPONDING SCENE

Firstly traced all sprite bodies in the physics editor,then add the corresponding generated plist in the resource folder of the project and add 4 classes(GB2ShapeCache-x.h,GB2ShapeCache-x.cpp,GLES-Render.h,GLES-Render.cpp),then make the bodies as below:
GB2ShapeCache::sharedGB2ShapeCache()->;addShapesWithFile("generated plist name");
void scene::addNewSpriteWithCoords() {

CCSize winSize = CCDirector::sharedDirector()->;getWinSize();

//BODY OF SPRITE1 b2BodyDef bodyDef1; bodyDef1.type=b2_dynamicBody; bodyDef1.position.Set((x position)/PTM_RATIO,(y position) /PTM_RATIO); bodyDef1.userData = sprite1;

body1 = world->CreateBody(&bodyDef1);

// add the fixture definitions to the body

GB2ShapeCache *sc1 = GB2ShapeCache::sharedGB2ShapeCache(); sc1->addFixturesToBody(body1,”name of sprite1 in plist”, sprite1);

sprite1->setAnchorPoint(sc1->anchorPointForShape(“name of sprite1 in plist”));

//Similarly body2 for sprite2 and for other sprites in the array

}
//MUST SCHEDULE THE UPDATE FUNCTION IN THE INITIALISATION FUNCTION OF THE SCENE USING LINE:

scene->scheduleUpdate;

//REMOVE SPRITE AND THEIR BODIES ON TOUCH
void scene::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event) { CCTouch* touch = (CCTouch*)touches->anyObject(); CCObject* rect; CCARRAY_FOREACH(arr, rect) { if (((CCSprite*)rect)!=NULL) { CCPoint touchPoint = CCDirector::sharedDirector()->convertToGL(touch->getLocationInView());

touchPoint = ((CCSprite*)rect)->convertToNodeSpace(touchPoint);

//MAKE THE BOUNDING BOX AS THE BODY IS DYNAMIC AND CAN ROTATE IN ANY DIRECTION

CCRect *box= new CCRect(((CCSprite*)rect)->getOffsetPosition().x ,((CCSprite*)rect)->getOffsetPosition().y ,((CCSprite*)rect)->getTextureRect().size.width

,((CCSprite*)rect)->getTextureRect().size.height);

if(box->containsPoint(touchPoint)) {

//REMOVE SPRITE

this->removeChild(((CCSprite*)rect),true); if(((CCSprite*)rect)==sprite1) { sprite1=NULL;

//REMOVE BODY

world->DestroyBody(body1); }

//Similarly for other sprites in the array

}

}

}

1,412 total views, 1 views today

Share this Onfacebook-2649279twitter-6030952linkedin-5686937google-3837793 Tags: android, C++, cocos2dx, Game-development, ios