1 2 // written in the D programming language 3 4 module samples.Tumble; 5 6 import dchip.all; 7 8 import samples.ChipmunkDemo; 9 10 static cpSpace *space; 11 static cpBody *staticBody; 12 13 static void 14 update(int ticks) 15 { 16 enum int steps = 3; 17 enum cpFloat dt = 1.0f/60.0f/cast(cpFloat)steps; 18 19 for(int i=0; i<steps; i++){ 20 cpSpaceStep(space, dt); 21 22 // Manually update the position of the static shape so that 23 // the box rotates. 24 cpBodyUpdatePosition(staticBody, dt); 25 26 // Because the box was added as a static shape and we moved it 27 // we need to manually rehash the static spatial hash. 28 cpSpaceReindexStatic(space); 29 } 30 } 31 32 static cpSpace * 33 init() 34 { 35 staticBody = cpBodyNew(INFINITY, INFINITY); 36 37 cpResetShapeIdCounter(); 38 39 space = cpSpaceNew(); 40 space.gravity = cpv(0, -600); 41 42 cpBody *_body; 43 cpShape *shape; 44 45 // Vertexes for the bricks 46 int num = 4; 47 cpVect verts[] = [ 48 cpv(-30,-15), 49 cpv(-30, 15), 50 cpv( 30, 15), 51 cpv( 30,-15), 52 ]; 53 54 // Set up the static box. 55 cpVect a = cpv(-200, -200); 56 cpVect b = cpv(-200, 200); 57 cpVect c = cpv( 200, 200); 58 cpVect d = cpv( 200, -200); 59 60 shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, a, b, 0.0f)); 61 shape.e = 1.0f; shape.u = 1.0f; 62 shape.layers = NOT_GRABABLE_MASK; 63 64 shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, b, c, 0.0f)); 65 shape.e = 1.0f; shape.u = 1.0f; 66 shape.layers = NOT_GRABABLE_MASK; 67 68 shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, c, d, 0.0f)); 69 shape.e = 1.0f; shape.u = 1.0f; 70 shape.layers = NOT_GRABABLE_MASK; 71 72 shape = cpSpaceAddShape(space, cpSegmentShapeNew(staticBody, d, a, 0.0f)); 73 shape.e = 1.0f; shape.u = 1.0f; 74 shape.layers = NOT_GRABABLE_MASK; 75 76 // Give the box a little spin. 77 // Because staticBody is never added to the space, we will need to 78 // update it ourselves. (see above). 79 // NOTE: Normally you would want to add the segments as normal and not static shapes. 80 // I'm just doing it to demonstrate the cpSpaceReindexStatic() function. 81 staticBody.w = 0.4f; 82 83 // Add the bricks. 84 for(int i=0; i<3; i++){ 85 for(int j=0; j<7; j++){ 86 _body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts.ptr, cpvzero))); 87 _body.p = cpv(i*60 - 150, j*30 - 150); 88 89 shape = cpSpaceAddShape(space, cpPolyShapeNew(_body, num, verts.ptr, cpvzero)); 90 shape.e = 0.0f; shape.u = 0.7f; 91 } 92 } 93 94 return space; 95 } 96 97 static void 98 destroy() 99 { 100 cpBodyFree(staticBody); 101 ChipmunkDemoFreeSpaceChildren(space); 102 cpSpaceFree(space); 103 } 104 105 chipmunkDemo Tumble = { 106 "Tumble", 107 null, 108 &init, 109 &update, 110 &destroy, 111 };