Box2d + oF006

Hello johnavila2!

In the Box2D manual ( you find a ContactListener Class. You then have to register this class via something like

world->SetContactListener(new MyContactListener());<- something like this, not tested!!!  

If a new contact occurs you get informed in the Add () method of your contact listener, so you might implement a ofNotifyEvent here… or whatever you need.


ok here is working example of contactlistener

greetings ascorbin


this is my example with openCv + Box2D


I Want To make better the reaction, like mouse evetns but with people anyone have idea how can i make this??

I would like to download the ofxBox2d from Vanderlin’s google code, but I don’t find the way to download the addon. I just can read the code, but I suppose there is a easy way to download it, not copying one by one.
Thanks for the help

you need an svn client to download the files from svn.
svn is used for version control.

i personally use versions (, although you’ll be able to find some free svn clients for download… just give it a google.


hi guys i just download ofxbox2d and ascorbin’s example. when i compile there some errors say:
ofxbox2d\ofxbox2dpolygon.h(124) : error C2057: expected constant expression
ofxbox2d\ofxbox2dpolygon.h(124) : error C2466: cannot allocate an array of constant size 0
when i check the corresponding code, i do find this in ofxbox2dpolygon.h:
int count = (int)vertices.size();
b2Vec2 vertexArray[count];
as far as i know, C++ cannot allocate an array with a variable length.
does anyone come across the same error as me?


I’ve been playing around with this library, and it looks awesome. I want to implement the checkBounds, so objects are destroyed when out of sight. In the source code (odxBox2d.cpp) it says this in the update function:

// destroy the object if we are out of the bounds  
	if(bCheckBounds) {  
		/* need to add a bit of code to remove the bodies */  

Anyone who knows how to destroy an object from that function?

And any way you want to share the code on GitHub so people can contribute?


  • Rune

Okay I find out. It’s an ugly hack, but this code with remove all bodies with a position higher than 30.

		b2Body* node = world->GetBodyList();  
		while (node)  
			b2Body* b = node;  
			node = node->GetNext();  
			if (b->GetPosition().y > 30)  
				printf("Body destroyed \n");  

this is awesome - I will try it out and commit the code

hey. sorry to cross post but i have been playing with box2d and loving it, although i keep getting the following error. even when just running the example. everything seems to run fine but this floods the console. is there a way to fix this or suppress the error message? any help greatly appreciated:

2010-02-18 11:42:06.343 emptyExample[1368:10b] GLUT Warning: GL error: invalid operation  

(XCode, OSX 10.5, OF 0061)

Hi guys.

I’m running Box2d, with some custom shapes in a vector.

I’m extending the class from the ofxBox2dRect object. Additionally, when I create them, I do the standard:

  • setPhysics()
  • setBounds()
  • setup()

and then push_back into my vector. This works great, essentially throwing them into my vector to keep track of and getting thrown into the box2D (through the setup method).

However, when I try to remove them, I crash my app OR they are removed visually, but still take up space in the box2D world (effectively causing invisible collisions).

I attempt to destroy the body manually much the way mentioned earlier in the thread.


and then remove from the vector using the erase method.

Any ideas on why this is happening, or if there’s something more specific I need to do to clean up the box2D world object?


I have the same problem.
Have you find a solution to your problem?
Thanks you!

Someone can explain me how to change de color of the particles using the contactListener once they collide each other??

I can’t imagine how to do that using userData.


i found a small bug in,

ofxBox2dBaseShape :: addForce(ofPoint pt, ofPoint amt);

looks like pt and amt are the other way around.
in the manual its documented as,

myBody->ApplyForce(myForce, myPoint)  

it took me a few tests to work out what values ApplyForce likes…
and if you’re trying to add a force to a circle, for example - pushing a circle in a certain direction.
i found this to work the best,

b2Vec2 frc = b2Vec2( 1, -1 );    // arbitrary force value.  
b2Vec2 pt  = circle.body->GetWorldCenter();   // center point of body  
circle.body->ApplyForce( frc, pt );  


i had to work out how to raycast in box2d and have written some code for ofxBox2d to do this. ray casting is basically running a line in box2d and testing which shapes hit that line and at what points.

in ofxBox2d.h,

void raycast ( const ofPoint &p1, const ofPoint &p2, int maxHits = 1, vector<ofPoint>* hitPoints = NULL, vector<b2Shape*>* shapes = NULL );  

the method takes two points which describe the line.
maxHits is the maximum number of shapes to find hitting the line.
hitPoints is a vector for storing the ofPoint’s where the line and shapes make contact.
shapes is a vector which stores a pointer reference to the shapes the line makes contact with.

in ofxBox2d.cpp,

void ofxBox2d :: raycast ( const ofPoint &p1, const ofPoint &p2, int maxHits, vector<ofPoint>* hitPoints, vector<b2Shape*>* shapes )  
	b2Segment segment;  
	segment.p1	= b2Vec2( p1.x / OFX_BOX2D_SCALE, p1.y / OFX_BOX2D_SCALE );  
	segment.p2	= b2Vec2( p2.x / OFX_BOX2D_SCALE, p2.y / OFX_BOX2D_SCALE );  
	for( int i=0; i<maxHits; i++ )  
		float lambda = 1;  
		b2Vec2 normal;  
		b2Shape* shape = NULL;  
		shape = world->RaycastOne( segment, &lambda, &normal, false, NULL );  
		if( shape != NULL )  
			if( shapes != NULL )  
				shapes->push_back( shape );  
			if( hitPoints != NULL )  
				b2Vec2 hit;  
				hit = ( 1 - lambda ) * segment.p1 + lambda * segment.p2;  
				ofPoint hitPoint;  
				hitPoint.x = hit.x * OFX_BOX2D_SCALE;  
				hitPoint.y = hit.y * OFX_BOX2D_SCALE;  
				hitPoints->push_back( hitPoint );  
			lambda = MIN( lambda + 0.001, 1.0 );	// nudge lambda a little so it doesn't find the same shape twice.  
			segment.p1 = ( 1 - lambda ) * segment.p1 + lambda * segment.p2;  
			return;		// nothing hit.  
		float segmentLength;  
		segmentLength = ofDist( segment.p1.x, segment.p1.y, segment.p2.x, segment.p2.y );  
		if( segmentLength <= B2_FLT_EPSILON )  


worked out a much nicer way of raycasting in box2d.
i moved the functionality into ofxBox2dBaseShape, so now all shapes can query if they collide with a ray and at what point.

the raycast method takes 2 points that describe the ray and a optional hitPoint (point of collision). it returns a bool to say if the ray has hit the shape or not.

bool raycast ( const ofPoint& p1, const ofPoint& p2, ofPoint* hitPoint = NULL )  
	bool bHit = false;  
	if( body != NULL )  
		b2Shape* shape = body->GetShapeList();  
		b2Segment segment;  
		segment.p1	= b2Vec2( p1.x / OFX_BOX2D_SCALE, p1.y / OFX_BOX2D_SCALE );  
		segment.p2	= b2Vec2( p2.x / OFX_BOX2D_SCALE, p2.y / OFX_BOX2D_SCALE );  
		const b2XForm xf = shape->GetBody()->GetXForm();  
		float lambda = 1;  
		b2Vec2 normal;  
		b2SegmentCollide hitResult;  
		hitResult = shape->TestSegment( xf, &lambda, &normal, segment, 1 );  
		if( hitResult == e_hitCollide )					// ray has hit shape.  
			bHit = true;  
		else if( hitResult == e_missCollide )			// ray does not hit shape.  
			bHit = false;  
		else if( hitResult == e_startsInsideCollide )	// ray starts inside shape.  
			bHit = true;  
		if( bHit && hitPoint != NULL )  
			hitPoint->x = ( 1 - lambda ) * segment.p1.x + lambda * segment.p2.x;  
			hitPoint->y = ( 1 - lambda ) * segment.p1.y + lambda * segment.p2.y;  
			hitPoint->x *= OFX_BOX2D_SCALE;  
			hitPoint->y *= OFX_BOX2D_SCALE;  
	return bHit;  

hey ya’ll,

been playing around with the contact listener example provided by ascorbin and created a tiny demo using balls which when collide change color on contact. was just curious to see how this would look as im thinking of including it in a project.

here you go,


really nice contact detection example!
i will tell this to Japanese oF forum folks.


Damn it Julapy nailed it again! :wink:

hey, just added multi touch support to ofxBox2d for the iphone + ipad.
its basically just extending what the mouse is doing by creating a b2MouseJoint, although its now doing it for a multiple number of touches.

in ofxBox2d.h,


i had to define a maximum number of touch joints to correctly track touch ids. 5 is the max num supported by ofxiPhone - if it changes in the future, this value will need to be updated.

in ofxBox2d.h,

b2MouseJoint*		touchJoints[ OF_MAX_TOUCH_JOINTS ];  

touchJoints array.

in ofxBox2d.h,

void grabShapeDown ( float x, float y, int id = -1 );  
void grabShapeUp ( float x, float y, int id = -1 );  
void grabShapeDragged ( float x, float y, int id = -1 );  

added id variable to grab functions. -1 is the default and reserved for mouse. all iPhone touch ids are 0 to 4.

in ofxBox2d.cpp - init() function.

for( int i=0; i<OF_MAX_TOUCH_JOINTS; i++ )  
	touchJoints[ i ] = NULL;  

just realised typing all this out is a pain in the arse :slight_smile:

the only other changes are in,
grabShapeDown, grabShapeUp, grabShapeDragged methods.

its all in here.

what is the best way of adding code to ofxBox2d for future versions btw?