Clone this wiki locally
Welcome to the Chipmunk-Physics wiki!
Basic walkthrough examples (C++, but applicable to other languages)
Adding a bunch of static bodies (useful for very large tiled worlds)
cpSpace* space = cpSpaceNew(); cpVect gravity = cpv(0, -9.8); cpSpaceSetGravity(space, gravity); // each space has its own static body, so in the case of a large tiled world, we'll just add // shapes to that one body, which means that it's quite cheap. (this is equivalent to Box2D's adding // multiple fixtures to one body). cpBB bb = cpBBNew(x, y, x2, y2); cpShape *tileShape = cpBoxShapeNew2(space->staticBody, bb); cpShapeSetFriction(tileShape, 0.7); cpSpaceAddShape(space, tileShape);
And of course you can do that many many times, adding new shapes to the same static body but at different positions (for me it scales to millions of shapes, so there's no performance loss. My experience with box2d was not as awesome).
To delete a tile shape, do use the following:
cpSpaceRemoveShape(space, tileShape); cpShapeFree(tileShape)
Note that you must remove the shape before freeing it otherwise you will crash.
Creating a player body/shape
Generally speaking, games make the player body a "pill" or elliptical shape, or just have 2 circles on top of each other. This prevents snagging on edges of objects.
cpBody* body = cpBodyNew(0.5, INFINITY); cpSpaceAddBody(space, body); cpBodySetPos(body, cpv(x, y)); cpShape *circleShape = cpCircleShapeNew(body, 0.5, cpvzero); cpShapeSetFriction(circleShape, 0.5); cpSpaceAddShape(space, circleShape);
The second parameter to the new body call is INFINITY as this is the moment of inertia, (basicaly rotational friction), as we of course don't want the player to be spinning around.
Using sensors to allow the player to jump
So basically when the player wants to jump, you want to apply a force. If you applied the force each tick as long as the spacebar was pressed, you'd probably fly off the map. So we need to set it on a delay timer (unrelated to chipmunk, use whatever you or your language provides as timers).
But that still means that the player can jump in mid-air, obviously a problem.
Sensors are the way to solve this. The basic idea is to create a "foot sensor" attached to the player's feet. When the sensor reports contacts (through a callback), we modify the player data to let us know that the player has their feet on the ground and jumping is then allowed. Of course, the reverse happens when a contact is reported to have left.
Code creating a sensor doing this: