Integrating Chipmunk into Objective C iPhone Games


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.

  1. #1 by Richy on April 15th, 2009

    Hey u r so awesome. Would it be possible if u could send me ur command line on stickwars bcuz I’m trying to make my own game
    for the itouch and I’m kinda new at this stuff. Thanx my email address is ammadat@pacbell.net

    • #2 by Eric on April 15th, 2009

      I don’t quite understand what you mean by a ‘command line’ for the game. However, I will be posting various parts of the source for the game to this website over the next few weeks, so check pack for tips and code samples.

  2. #3 by Sean Carmody on July 16th, 2009

    Hi Eric,

    Excellent job on Stick Wars. I actually have a question on this specific blog subject.

    If you are using Chipmunk and you have the “update” function running, how do you update a score from within “update”? I can’t seem to reach any labels that I had set at initialization, and references to “self” don’t work. The labels are not within the “update” function.

    Do you have any tips or recommendations?

    Thank you

    • #4 by Eric on July 16th, 2009

      Okay, I believe you might want to check over a few tutorials about OOP with Objective C. Try http://www.otierney.net/objective-c.html it is pretty good.

      Basically, you need the follow the instructions above so that you can call the step: method inside of an object that holds references to the labels you create (make sure to store pointers to the labels when you create them).

  3. #5 by Xun Cai on July 18th, 2009

    Hi Eric,
    Thanks for you postings and you game is great.
    I have a question about Optimization of Chipmunk.
    I am using it to make a game called 9000BC where there are a lot of soldiers.
    I am testing the performance now. I noticed that if I have 20 or 30 chipmunk objects (body and shape) in the space, then the speed of the game drop down. Also, sometimes it runs faster sometimes it runs slower.

    I notice that your game runs smoothly. Did you add the chipmunk body and shape when you throw the enemies to the sky and remove it from the chipmunk space once done?

    Can you tell me some of the strategies you apply to make things run smoothly?

    Thanks
    Xun Cai

    • #6 by Eric on July 18th, 2009

      To be honest, Chipmunk isn’t great when you try to add and remove objects very often, so I just add every figure on the screen to Chipmunk as soon as it is ‘live’ and only remove it a half second or so after it dies.

      This is because if you try to remove objects during collision events, you get unpredictable crashes. I might be able to make it run a bit smoother by trying to keep Chipmunks objects to a minimum, but I’m scared of trying it out cause playing around with Chipmuck objects led to a LOT of hard-to-track crashes in the beginning that hung around for many weeks.

      I’ve found that about 20-30 objects in Chipmunk is all that StickWars will support at once on an 1-gen 400 mhz processor (iPhone 2G, 3G, iPod Touch 1G).

      The optimizations I mainly did was to make sure what ever gameplay was going on, I wouldn’t have to create a lot of new objects at once. So I took the trouble to create caches for objects like ‘explosions’ (which are actually additional Chipmunk objects themselves!) as well as the particle animations which represents them visually.

      It was a lot more work at first, but now it works nicely as I just keep an array of these objects and my LevelController pulls them in as needed from the cache, or does nothing if the cache is empty (too many explosions going on at once, like 10 or 15).

(will not be published)

  1. No trackbacks yet.