Game Development Reference
In-Depth Information
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body-> CreateFixture(&fixtureDef);
[sprite setPhysicsBody:body];
}
First, a sprite is created from the CCSpriteBatchNode by using PhysicS-
prite 's spriteWithTexture initializer and supplying a CGRect that's 32×32
pixels in size, to randomly pick one of the tileset's tiles as the sprite's image.
Cocos2d provides the PhysicsSprite class. It's essentially a regular CCSprite
that has an additional physics body instance variable. It uses the physics body to set the
sprite's position and rotation every time the sprite is rendered. This has the added ad-
vantage that you don't need to manually update the sprite's position and rota-
tion properties, and it works well with ARC because you don't need to store the
sprite with the body's SetUserData(void* data) function.
But I do store the sprite in the body's userdata anyway, because I need the sprite
later on during collision detection in order to tint its color to visualize the collision. Be-
cause the userdata is a void* pointer, assigning an Objective-C object to void*
with ARC enabled requires a special bridge cast, like this:
body-> SetUserData((__bridge void*)sprite);
You also need a bridge cast to obtain the physics sprite from the body's userdata :
PhysicsSprite* sprite = (__bridge PhysicsSprite*)body-> GetUserData();
After the sprite, a body is created, but this time the b2BodyDef type property is set to
b2_dynamicBody , which makes it a dynamic body that can move around and col-
lide with other dynamic bodies. Later, when you're iterating over the bodies in the
world, this allows you to quickly access the body's sprite.
The body's shape is a b2PolygonShape set to a box shape that's half a meter in
size. The SetAsBox method creates a box shape that's twice the given width and
Search Nedrilad ::




Custom Search