Chipmunk2D 6.2.1

Chipmunk2D是一个基于MIT协议的2D刚体物理仿真库。设计宗旨:极快、可移植、稳定、易用。出于这个原因,它已经被用于数百多游戏横跨了几乎所有系统。这些游戏包括了在iPhoneAppStore上的一些顶级出色的如Night Sky等许多TOP1游戏。这几年来,我投入了大量的时间来发展Chipmunk,才使得Chipmunk走到今天。如果您发现Chipmunk2D为您节省了许多事件,不妨考虑捐赠下。这么做会使一个独立游戏制作者非常开心!

首先,我要非常感谢ErinCatto(译者注:Box2D作者), 早在2006年的时候,Chipmunk的冲量求解器便是受到他的范例代码的启发而完成。(现在已经发展成一个成熟的物理引擎:Box2D.org) 他的持久接触的想法允许对象的稳定堆栈只进行极少的求解器迭代,而我以前的求解器为了让模拟稳定模拟会产生大量的对象或者会消耗大量的CPU资源。

Hello Chipmunk(World)

Hello world Chipmunk 风格。创建一个模拟,模拟一个球掉落到一个静态线段上然后滚动出去,并打印球的坐标。

  1. #include <stdio.h>
  2. #include <chipmunk.h>
  3. int main(void){
  4. // cpVect是2D矢量,cpv()为初始化矢量的简写形式
  5. cpVect gravity = cpv(0, -100);
  6. // 创建一个空白的物理世界
  7. cpSpace *space = cpSpaceNew();
  8. cpSpaceSetGravity(space, gravity);
  9. // Add a static line segment shape for the ground.
  10. // We'll make it slightly tilted so the ball will roll off.
  11. // We attach it to space->staticBody to tell Chipmunk it shouldn't be movable.
  12. cpShape *ground = cpSegmentShapeNew(space->staticBody, cpv(-20, 5), cpv(20, -5), 0);
  13. cpShapeSetFriction(ground, 1);
  14. cpSpaceAddShape(space, ground);
  15. // Now let's make a ball that falls onto the line and rolls off.
  16. // First we need to make a cpBody to hold the physical properties of the object.
  17. // These include the mass, position, velocity, angle, etc. of the object.
  18. // Then we attach collision shapes to the cpBody to give it a size and shape.
  19. cpFloat radius = 5;
  20. cpFloat mass = 1;
  21. // The moment of inertia is like mass for rotation
  22. // Use the cpMomentFor*() functions to help you approximate it.
  23. cpFloat moment = cpMomentForCircle(mass, 0, radius, cpvzero);
  24. // The cpSpaceAdd*() functions return the thing that you are adding.
  25. // It's convenient to create and add an object in one line.
  26. cpBody *ballBody = cpSpaceAddBody(space, cpBodyNew(mass, moment));
  27. cpBodySetPos(ballBody, cpv(0, 15));
  28. // Now we create the collision shape for the ball.
  29. // You can create multiple collision shapes that point to the same body.
  30. // They will all be attached to the body and move around to follow it.
  31. cpShape *ballShape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero));
  32. cpShapeSetFriction(ballShape, 0.7);
  33. // Now that it's all set up, we simulate all the objects in the space by
  34. // stepping forward through time in small increments called steps.
  35. // It is *highly* recommended to use a fixed size time step.
  36. cpFloat timeStep = 1.0/60.0;
  37. for(cpFloat time = 0; time < 2; time += timeStep){
  38. cpVect pos = cpBodyGetPos(ballBody);
  39. cpVect vel = cpBodyGetVel(ballBody);
  40. printf(
  41. "Time is %5.2f. ballBody is at (%5.2f, %5.2f). It's velocity is (%5.2f, %5.2f)\n",
  42. time, pos.x, pos.y, vel.x, vel.y
  43. );
  44. cpSpaceStep(space, timeStep);
  45. }
  46. // Clean up our objects and exit!
  47. cpShapeFree(ballShape);
  48. cpBodyFree(ballBody);