Getting started with PhysicsEditor and Sparrow and Box2d

2012-05-07 Andreas Löw Get Sourcecode from GitHub

This is a complete sample project using PhysicsEditor to create physics shapes for Sparrow SDK. You can add sprites by tapping the screen, remove them by tapping on existing sprites. It also reacts to the accelerometer changing the gravity vector when the device is tilted.

The code itself is well documented - this is why I just want to put some spotlight on the PhysicsEditor integration.

I assume that your are already familiar with the basic of PhysicsEditor. If not have a look at the tutorial section ;-)

The complete code is available on GitHub or can be downloaded as archive at the end of the blog post.

Loading the data

The loading of the created shapes file is done using the included GB2ShapeCache class which loads physics shapes for iOS devices:

[[GB2ShapeCache sharedShapeCache] addShapesWithFile:@"shapedefs.plist"];

Creating a sprite and attaching a physics shape to it

To create a sprite with physics connection you need to create the sprite first, then attach the image object:

// Create SPSprite object
SPSprite *sprite = [SPSprite sprite];

// Set SPSprite object position to touch position
sprite.x = p.x;
sprite.y = p.y;

// Create SPImage object
SPImage *image = [SPImage imageWithTexture:[_textures objectForKey:name]];

// Add SPImage as a child to SPSprite
[sprite addChild:image];

To lign up the physics shapes with the visuals set the anchor point retrieved from the shapes file:

// Apply anchor point of selected shape to SPImage object
[self setAnchorPoint:[[GB2ShapeCache sharedShapeCache] anchorPointForShape:name]

Next create a physics body object:

// Create physics body
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

// Remember that Y-axis directions in Sparrow and Box2D are opposite
bodyDef.position.Set(sprite.x/PTM_RATIO, (m_debugDraw->_screenHeight-sprite.y)/PTM_RATIO);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);

Finally attach the fixtures to the body:

// Add the fixture definitions to the body
[[GB2ShapeCache sharedShapeCache] addFixturesToBody:body forShapeName:name];

Did you like the tutorial? Please share!

Source code available for download

The source code is available on GitHub. Clone it using git:

git clone

or download one of the archives: PhysicsEditor-Sparrow-Box2d.tar.gz