Saturday, April 10, 2010

2D Terrain Mapper for use with iPhone SDK, Coco2D, Chipmunk and SpaceManger

There are a number of fantastic libraries available for writing games on the iPhone. Cocos2D is an amazing 2D graphics engine. Chipmunk is an equally awesome physics library. And SpaceManager allows you to integrate chipmunk with Cocos2D without leaving the comfort of Objective C. The problem I had was synching the graphic images I was using in Cocos2D with the shapes I defined in Chipmunk. I could assign simple shapes to simple graphic objects easily enough, but when it came to a dynamically changing moving terrain, that was another story. So after hunting around for a solution, I found some code for a color picker for the iPhone by the helpful folks over at After hunting around the web some more, I was able to find a few other missing pieces that allowed me to cobble together the code I needed. I've gathered a demo file together and attached it to this post. It's not as clean as I would like it to be, and surely some of it could be written better, but hopefully it will be helpful to some of you out there. Basically, with this demo project, you can see how you can take a PNG of a ground terrain set against a transparent background and this project will follow that terrain by starting at the top of each column in the image and working it's way down until it hits the first non-transparent pixel in each column. It then uses that data to produce segments for chipmunk, which allow your game pieces to follow the terrain accurately.

The file is located here. It's a zip file of an Xcode project.