Chipmunk2D 6.2.1
优质
小牛编辑
133浏览
2023-12-01
Chipmunk2D是一个基于MIT协议的2D刚体物理仿真库。设计宗旨:极快、可移植、稳定、易用。出于这个原因,它已经被用于数百多游戏横跨了几乎所有系统。这些游戏包括了在iPhoneAppStore上的一些顶级出色的如Night Sky等许多TOP1游戏。这几年来,我投入了大量的时间来发展Chipmunk,才使得Chipmunk走到今天。
首先,我要非常感谢ErinCatto(译者注:Box2D作者), 早在2006年的时候,Chipmunk的冲量求解器便是受到他的范例代码的启发而完成。(现在已经发展成一个成熟的物理引擎:Box2D.org) 他的持久接触的想法允许对象的稳定堆栈只进行极少的求解器迭代,而我以前的求解器为了让模拟稳定模拟会产生大量的对象或者会消耗大量的CPU资源。
Hello Chipmunk(World)
Hello world Chipmunk 风格。创建一个模拟,模拟一个球掉落到一个静态线段上然后滚动出去,并打印球的坐标。
#include <stdio.h>
#include <chipmunk.h>
int main(void){
// cpVect是2D矢量,cpv()为初始化矢量的简写形式
cpVect gravity = cpv(0, -100);
// 创建一个空白的物理世界
cpSpace *space = cpSpaceNew();
cpSpaceSetGravity(space, gravity);
// Add a static line segment shape for the ground.
// We'll make it slightly tilted so the ball will roll off.
// We attach it to space->staticBody to tell Chipmunk it shouldn't be movable.
cpShape *ground = cpSegmentShapeNew(space->staticBody, cpv(-20, 5), cpv(20, -5), 0);
cpShapeSetFriction(ground, 1);
cpSpaceAddShape(space, ground);
// Now let's make a ball that falls onto the line and rolls off.
// First we need to make a cpBody to hold the physical properties of the object.
// These include the mass, position, velocity, angle, etc. of the object.
// Then we attach collision shapes to the cpBody to give it a size and shape.
cpFloat radius = 5;
cpFloat mass = 1;
// The moment of inertia is like mass for rotation
// Use the cpMomentFor*() functions to help you approximate it.
cpFloat moment = cpMomentForCircle(mass, 0, radius, cpvzero);
// The cpSpaceAdd*() functions return the thing that you are adding.
// It's convenient to create and add an object in one line.
cpBody *ballBody = cpSpaceAddBody(space, cpBodyNew(mass, moment));
cpBodySetPos(ballBody, cpv(0, 15));
// Now we create the collision shape for the ball.
// You can create multiple collision shapes that point to the same body.
// They will all be attached to the body and move around to follow it.
cpShape *ballShape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero));
cpShapeSetFriction(ballShape, 0.7);
// Now that it's all set up, we simulate all the objects in the space by
// stepping forward through time in small increments called steps.
// It is *highly* recommended to use a fixed size time step.
cpFloat timeStep = 1.0/60.0;
for(cpFloat time = 0; time < 2; time += timeStep){
cpVect pos = cpBodyGetPos(ballBody);
cpVect vel = cpBodyGetVel(ballBody);
printf(
"Time is %5.2f. ballBody is at (%5.2f, %5.2f). It's velocity is (%5.2f, %5.2f)n",
time, pos.x, pos.y, vel.x, vel.y
);
cpSpaceStep(space, timeStep);
}
// Clean up our objects and exit!
cpShapeFree(ballShape);
cpBodyFree(ballBody);