Getting started with PhysicsEditor and Sparrow and Box2d

Andreas Löw
Getting started with PhysicsEditor and Sparrow and Box2d
Last update: More than 3 months ago

What you are going to learn:

  • create a sprite and attach the image object
  • create a physics body object
  • attach the fixtures to the body

The complete code is available on GitHub

Sparrow Framework Logo

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 line 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]
            forImage:image];

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];