1 2 // written in the D programming language 3 4 module samples.Simple; 5 6 import dchip.all; 7 8 import samples.ChipmunkDemo; 9 10 import std.math:sqrt; 11 12 static cpSpace *space; 13 14 // Init is called by the demo code to set up the demo. 15 static cpSpace * 16 init() 17 { 18 // Create a space, a space is a simulation world. It simulates the motions of rigid bodies, 19 // handles collisions between them, and simulates the joints between them. 20 space = cpSpaceNew(); 21 22 // Lets set some parameters of the space: 23 // More iterations make the simulation more accurate but slower 24 space.iterations = 1; 25 // Give it some gravity 26 // space.gravity = cpv(0, -100); 27 28 // Create A ground segment along the bottom of the screen 29 // By attaching it to &space.staticBody instead of a body, we make it a static shape. 30 cpShape *ground = cpSegmentShapeNew(space.staticBody, cpv(-320,-240), cpv(320,-240), 0.0f); 31 // Set some parameters of the shape. 32 // For more info: http://code.google.com/p/chipmunk-physics/wiki/cpShape 33 ground.e = 1.0f; ground.u = 1.0f; 34 ground.layers = NOT_GRABABLE_MASK; // Used by the Demo mouse grabbing code 35 // Add the shape to the space as a static shape 36 // If a shape never changes position, add it as static so Chipmunk knows it only needs to 37 // calculate collision information for it once when it is added. 38 // Do not change the postion of a static shape after adding it. 39 cpSpaceAddShape(space, ground); 40 41 for(int i=-5; i<=5; i++){ 42 cpFloat radius = 25.0f; 43 cpFloat mass = 1.0f; 44 // cpBody *ballBody = cpBodyNew(INFINITY, cpMomentForCircle(mass, 0.0f, radius, cpvzero)); 45 cpBody *ballBody = cpBodyNew(mass, INFINITY); 46 ballBody.p = cpv((5 + 2*radius)*i, 200); 47 cpSpaceAddBody(space, ballBody); 48 49 cpShape *ballShape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero)); 50 ballShape.e = 0.0f; ballShape.u = 0.9f; 51 52 float stiffness = 30; 53 float damping = 2.0f*sqrt(stiffness*ballBody.m)*cpfpow(1.1f, i); 54 // float stiffness = 30; 55 // float damping = 0.0; 56 cpSpaceAddConstraint(space, cpDampedSpringNew(space.staticBody, ballBody, cpv((5 + 2*radius)*i, 0), cpvzero, 0, stiffness, damping)); 57 } 58 59 return space; 60 } 61 62 // Update is called by the demo code each frame. 63 static void 64 update(int ticks) 65 { 66 // Chipmunk allows you to use a different timestep each frame, but it works much better when you use a fixed timestep. 67 // An excellent article on why fixed timesteps for game logic can be found here: http://gafferongames.com/game-physics/fix-your-timestep/ 68 cpSpaceStep(space, 1.0f/60.0f); 69 } 70 71 // destroy is called by the demo code to free all the memory we've allocated 72 static void 73 destroy() 74 { 75 ChipmunkDemoFreeSpaceChildren(space); 76 cpSpaceFree(space); 77 } 78 79 chipmunkDemo Simple = { 80 "Simple", 81 null, 82 &init, 83 &update, 84 &destroy, 85 };