When working with Cocos 2d iPhone, a lot of the sample code provided that shows how to hook into the Chipmunk physics engine using static functions outside of any Objective C object. While this is the most straightforward way to get the engine up and running, it restricts what you can do later on.
Instead, you need to create a static function which takes two parameters, the object being updated and the objects container. Here’s some code:
This is the static function which goes outside your class implementation. Notice that we don’t actually do any of the object updates here. This is good, because we can’t access any of the internal state in the container in this method.
static void updateEachShapeCallback(void *ptr, void *parent) { GameController *parentObject = (GameController *)parent; [parentObject updateShape: ptr]; }
Note that my container, called GameController, is a CocosNode so when were ready to start the game we can call
[self schedule: @selector(step:)];
to update the shapes.
This goes inside the implementation of your container.
- (void) step: (ccTime) delta { int steps = 1; cpFloat dt = delta/(cpFloat)steps; for(int i=0; iactiveShapes, &updateEachShapeCallback, self); cpSpaceHashEach(space->staticShapes, &updateEachShapeCallback, self); }
Add in the updateShape:(void *)ptr method to your GameController interface file and then implement as
- (void) updateShape:(void *)ptr { cpShape *shape = (cpShape*) ptr; Touchable *obj = shape->data; if(obj) { cpBody *body = shape->body; [obj setPosition: cpv( body->p.x, body->p.y)]; [obj setRotation: (float) CC_RADIANS_TO_DEGREES( -body->a )]; // do whatever else you want here! you have all the the state you should need! // just avoiding creating objects anywhere from here as that will slow your game down } }
I adopted this solution from instructions I found at Using native Objective-C methods for C Callbacks.
Comments
Leave a comment Trackback