I happened upon the Appcelerator Open Mobile Marketplace the other day, and started looking through the modules. One that caught my eye was the Box2D module. Earlier this year, we’d been dabbling with Cocos2d which is a game engine for iPhone, which uses Box2D as one of the physics engine you could use inside it.
Box2D is an open source library originally written in C that has been ported to Flash, Java, C++, Objective C and is widely popular in the game community. It’s not a huge stretch to see a Ti module adaptor being placed over the Objective C code, also nice because it should perform well.
I had a million and one things to do, so of course I dropped them all to see just what this shiny new bauble could do. Right now the module is in beta and there’s zero documentation, so the best thing is to check out some examples like pinball or a Hello World (more or less), and peek at the Objective C source code for a couple proxy classes, like Body and World.
Running the example from the github repository, you get a square and a ball that basically start at the top of the screen and fall down (and off) the screen.
Here’s the code with no floor:
To get a floor for these objects to land on, I added this:
But then I wanted to see if the objects would tumble down a hill, so the floor needed to have an angle to it. This is where examining the implementation of the World proxy object came in handy. the world.addBody(aBody) function returns a handle to the body it added. With that in hand, you can then apply methods from the Body proxy object implementation, and there happens to be one in there named setAngle(someDegree). That led to this code:
Lastly, I wanted to see if I could put up a wall that would let the ball bounce off the floor, roll down and then be stopped by the intersection of the wall and floor. Here’s how:
I’m looking forward to playing with Box2D module in more detail, maybe over Christmas break. Hope you gained a little insight into its workings in Titanium Appcelerator.