Game Development Reference
In-Depth Information
Adding Boxes to the Box2D World
With a static body containing the objects within screen boundaries, all that's missing is
something to be kept within the screen boundaries. How about little boxes, then?
I've added David Gervais' orthogonal tileset image dg_grounds32.png to the Re-
sources folder of the PhysicsBox2D01 project. The tiles are 32×32 pixels, so they
make perfect 1×1-meter boxes.
The addNewSpriteAt method shown in Listing 12-4 is part of the cocos2d Box2D
application template project but slightly modified to make use of all the tiles in the tile-
Listing 12-4. Adding a New Dynamic Body with a Sprite
-(void) addNewSpriteAtPosition:(CGPoint)pos
int idy = CCRANDOM_0_1() * TILESET_ROWS;
CGRect tileRect = CGRectMake(TILESIZE * idx, TILESIZE * idy, TILESIZE, TILESIZE);
PhysicsSprite* sprite = [PhysicsSprite spriteWithTexture:spriteTexture
CCNode* batchNode = [self getChildByTag:kTagBatchNode];
[batchNode addChild:sprite];
sprite.position = pos;
// Define the dynamic body.
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position = [self toMeters:pos];
b2Body* body = world-> CreateBody(&bodyDef);
body-> SetUserData((__bridge void*)sprite);
// Define a box shape for our dynamic body.
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(0.5f, 0.5f);
Search Nedrilad ::

Custom Search