Graphics Reference
In-Depth Information
Listing 11.4 Updated Physics Example with Walls and Multiple Crates
- ( void )addCrateWithFrame:( CGRect )frame
{
Crate *crate = [[ Crate alloc ] initWithFrame :frame];
[ self . containerView addSubview :crate];
cpSpaceAddBody ( self . space , crate. body );
cpSpaceAddShape ( self . space , crate. shape );
}
- ( void )addWallShapeWithStart:( cpVect )start end:( cpVect )end
{
cpShape *wall = cpSegmentShapeNew ( self . space -> staticBody , start, end, 1 );
cpShapeSetCollisionType (wall, 2 );
cpShapeSetFriction (wall, 0.5 );
cpShapeSetElasticity (wall, 0.8 );
cpSpaceAddStaticShape ( self . space , wall);
}
- ( void )viewDidLoad
{
//invert view coordinate system to match physics
self . containerView . layer . geometryFlipped = YES ;
//set up physics space
self . space = cpSpaceNew ();
cpSpaceSetGravity ( self . space , cpv ( 0 , - GRAVITY ));
//add wall around edge of view
[ self addWallShapeWithStart : cpv ( 0 , 0 ) end : cpv ( 300 , 0 )];
[ self addWallShapeWithStart : cpv ( 300 , 0 ) end : cpv ( 300 , 300 )];
[ self addWallShapeWithStart : cpv ( 300 , 300 ) end : cpv ( 0 , 300 )];
[ self addWallShapeWithStart : cpv ( 0 , 300 ) end : cpv ( 0 , 0 )];
//add a crates
[ self addCrateWithFrame : CGRectMake ( 0 , 0 , 32 , 32 )];
[ self addCrateWithFrame : CGRectMake ( 32 , 0 , 32 , 32 )];
[ self addCrateWithFrame : CGRectMake ( 64 , 0 , 64 , 64 )];
[ self addCrateWithFrame : CGRectMake ( 128 , 0 , 32 , 32 )];
[ self addCrateWithFrame : CGRectMake ( 0 , 32 , 64 , 64 )];
//start the timer
self . lastStep = CACurrentMediaTime ();
self . timer = [ CADisplayLink displayLinkWithTarget : self
selector : @selector (step:)];
[ self . timer addToRunLoop :[ NSRunLoop mainRunLoop ]
Search WWH ::




Custom Search