1 #import "ViewController.h"
2 #import
3 #import "chipmunk.h"
4
5 @interface Crate : UIImageView
6
7 @property (nonatomic, assign) cpBody *body;
8 @property (nonatomic, assign) cpShape *shape;
9
10 @end
11
12 @implementation Crate
13
14 #define MASS 100
15
16 - (id)initWithFrame:(CGRect)frame
17 {
18 if ((self = [super initWithFrame:frame])) {
19 //set image
20 self.image = [UIImage imageNamed:@"Crate.png"];
21 self.contentMode = UIViewContentModeScaleAspectFill;
22 //create the body
23 self.body = cpBodyNew(MASS, cpMomentForBox(MASS, frame.size.width, frame.size.height));
24 //create the shape
25 cpVect corners[] = {
26 cpv(0, 0),
27 cpv(0, frame.size.height),
28 cpv(frame.size.width, frame.size.height),
29 cpv(frame.size.width, 0),
30 };
31 self.shape = cpPolyShapeNew(self.body, 4, corners, cpv(-frame.size.width/2, -frame.size.height/2));
32 //set shape friction & elasticity
33 cpShapeSetFriction(self.shape, 0.5);
34 cpShapeSetElasticity(self.shape, 0.8);
35 //link the crate to the shape
36 //so we can refer to crate from callback later on
37 self.shape->data = (__bridge void *)self;
38 //set the body position to match view
39 cpBodySetPos(self.body, cpv(frame.origin.x + frame.size.width/2, 300 - frame.origin.y - frame.size.height/2));
40 }
41 return self;
42 }
43
44 - (void)dealloc
45 {
46 //release shape and body
47 cpShapeFree(_shape);
48 cpBodyFree(_body);
49 }
50
51 @end
52
53 @interface ViewController ()
54
55 @property (nonatomic, weak) IBOutlet UIView *containerView;
56 @property (nonatomic, assign) cpSpace *space;
57 @property (nonatomic, strong) CADisplayLink *timer;
58 @property (nonatomic, assign) CFTimeInterval lastStep;
59
60 @end
61
62 @implementation ViewController
63
64 #define GRAV