Skip to content

Instantly share code, notes, and snippets.

@slembcke
Created July 26, 2011 17:06
Show Gist options
  • Save slembcke/1107240 to your computer and use it in GitHub Desktop.
Save slembcke/1107240 to your computer and use it in GitHub Desktop.
Using blocks with Chipmunk callbacks
// Define this function somewhere
static void CallArbiterBlock(cpBody *body, cpArbiter *arbiter, void (^block)(cpArbiter *arbiter)){block(arbiter);}
// Then you can do this:
// __block makes the variable writable from within a block, otherwise they are read only.
__block cpVect impulseSum = cpvzero;
cpBodyEachArbiter(scaleStaticBody, (cpBodyArbiterIteratorFunc)CallArbiterBlock, ^(cpArbiter *arb){
impulseSum = cpvadd(impulseSum, cpArbiterTotalImpulse(arb));
});
// Convenient because the callback is in the same place as the code where the rest of your data probably is.
// You don't need to make one time use context structs. The compiler does it for you instead.
// *************************
// The alternative using function callbacks looks like this:
// If I had wanted to pass more than one value to the callback, it would have been annoying.
static void
ScaleIterator(cpBody *body, cpArbiter *arb, cpVect *sum)
{
(*sum) = cpvadd(*sum, cpArbiterTotalImpulse(arb));
}
cpVect impulseSum = cpvzero;
cpBodyEachArbiter(scaleStaticBody, (cpBodyArbiterIteratorFunc)ScaleIterator, &impulseSum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment