I have a 2D physics sandbox with a bunch of circles which resize on contact (the bigger one gets bigger, the smaller one gets smaller). I can resize the sprite fine, and I understand that you can't scale a B2Body - you need to destroy it and recreate it, but I'm not familiar enough with Box2D to do it yet.
Here's what I'm doing to resize the sprites:
std::vector<MyContact>::iterator pos;
for(pos = _contactListener->_contacts.begin();
pos != _contactListener->_contacts.end(); ++pos) {
MyContact contact = *pos;
b2Body *bodyA = contact.fixtureA->GetBody();
b2Body *bodyB = contact.fixtureB->GetBody();
if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
PaintBlob *spriteA = (PaintBlob *) bodyA->GetUserData();
PaintBlob *spriteB = (PaintBlob *) bodyB->GetUserData();
NSLog(@"spriteA: %@ is touching spriteB: %@", spriteA, spriteB);
if((spriteA.scale > spriteB.scale) && (spriteB.scale > 0)){
spriteA.scale = spriteA.scale + kSCALE_INCREMENT;
spriteB.scale = spriteB.scale - kSCALE_INCREMENT;
}else if (spriteA.scale >0) {
spriteB.scale = spriteB.scale + kSCALE_INCREMENT;
spriteA.scale = spriteA.scale - kSCALE_INCREMENT;
}
}
}
How do I resize (destroy/recreate) the Box2D body (a b2CircleShape?).
I think this is how you do it in C - from emanueleferonato.com (I am not enlightened enough to understand C):
// if I selected a body...
if (body) {
// I know it's a circle, so I am creating a b2CircleShape variable
var circle:b2CircleShape=body.GetShapeList() as b2CircleShape;
// getting the radius..
var r=circle.GetRadius();
// removing the circle shape from the body
body.DestroyShape(circle);
// creating a new circle shape
var circleDef:b2CircleDef;
circleDef = new b2CircleDef();
// calculating new radius
circleDef.radius=r*0.9;
circleDef.density=1.0;
circleDef.friction=0.5;
circleDef.restitution=0.2;
// attach the shape to the body
body.CreateShape(circleDef);
// determine new body mass
body.SetMassFromShapes();
}
return body;
Hi there you handsome devil.
Here's how:
//Radius is worked out by scale * kBLOBDIAMETER /2
contact.fixtureA->GetShape()->m_radius = (spriteA.scale * kBLOBLDIAMETER / 2) /PTM_RATIO;
contact.fixtureB->GetShape()->m_radius = (spriteB.scale * kBLOBLDIAMETER / 2) /PTM_RATIO;
bodyA->ResetMassData();
bodyB->ResetMassData();