How to destroy bodys in ofxBox2d?

Hi,

I am creating my objects using the following code

  
class CustomParticle : public ofxBox2dCircle {  
public:  
	CustomParticle() {}  
	  
	ofColor color;  
	  
	void draw() {  
		float radius = getRadius();  
		  
		glPushMatrix();  
		  
		glTranslatef(getPosition().x, getPosition().y, 0.0);  
		glRotatef(getRotation(), 0.0, 0.0, 1.0);  
		ofSetColor(color.r, color.g, color.b);  
		ofFill();  
		ofCircle(0, 0, radius * 1.2);	  
		  
		glPopMatrix();  
	}  
};  
  

and

  
void testApp::createCustomParticle(int x, int y) {  
	float radius = ofRandom(15.0, 30.0);  
	  
	CustomParticle p;  
	p.setPhysics(radius * 0.1, 0.56, 0.3);  
	p.setup(box2d.getWorld(), x, y, radius);  
	p.color.r = ofRandom(120, 255);  
	p.color.g = ofRandom(50, 105);  
	p.color.b = ofRandom(50, 205);  
	p.color.a = 0.5;  
	customParticles.push_back(p);  
}  

How can I destroy them?

I look at the Box2d documentation and I found I can use
box2d.world->DestroyBody(b2Body *body);
But I dont know how to implement that into my code, any help will be much appreciated

Cheers
rS

OK, I figure it out,

  
vector <CustomParticle>::iterator iter;  
	for (iter = customParticles.begin(); iter != customParticles.end(); iter++) {  
		box2d.world->DestroyBody(iter->body);  
		//cout << "destroy" << iter << endl;  
	}  

But, now the shapes that are attach to the bodys stay there motionless, and if I create more they al group to (0, 0) location, and the sketch crash

Any ideas?
rS

Fix it! for those interested

  
vector <CustomParticle>::iterator iter = customParticles.begin();  
	while (iter != customParticles.end()) {  
		iter->draw();  
		if (iter->isDead) {  
			box2d.world->DestroyBody(iter->body);  
			iter = customParticles.erase(iter);  
		}  
		else ++iter;  
	}  

Loving iterators!!!

Cheers
rS

1 Like

Thanks for this - it helped me out and pointed me in the right direction!
There is also a “destroyShape()” method in the base class for shapes, so you can call that on your shape to delete it as well.

For others who are searching or googling, to delete an object in ofxBox2d, you have to destroy it, which can be done several ways. In the snipped below, I have a vector called boxes, which contains many rectangles. I want to limit the number on screen, so if there are more than 200, I delete the oldest one (which is at the beginning of the vector) by calling destroyShape() on it. I then also erase the reference to that object from my vector.

  
  
if (boxes.size() > 200) {  
	boxes.begin()->destroyShape();  
	boxes.erase(boxes.begin());  
}  
  

Hello!
thanks for all the code, I just have one question, how could I destroyShape() not for the oldest, but for any one of the shapes, say like, I have 100 shapes on screen and I want to destroyShape() number 45.
=)
Thank you!