Developers Manual > Cocos2d-x > Advanced Features > Physics Engine > Chipmunk

Chipmunk

version: Cocos2d-x v2.x and earlier
update: Updated about 2 years ago

Introduction

Chipmunk is a game physics library written in C, that comes as part of Cocos2D. With it, you can make objects in your game behave like real life objects – they can be affected by gravity, collide into other objects, bounce around, and much more.

How Does Chipmunk Work?

Chipmunk simulates physics behavior in a “virtual Chipmunk space”. It’s your job to:

Add objects to this space.

Examples: shapes representing animals, flowers, or Muppets.

Tell Chipmunk about any forces that are acting upon these objects.

Examples: gravity, wind, alien tractor beams, etc.

Occasionally give Chipmunk time to update the simulation.

Examples: Chipmunk might calculate an animal falling a little bit more since last time, a flower bending slightly in the wind, of Gonzo might getting pulled in the air

Update your “real” Cocos2D world based on the physical simulation.

Examples: Set your animal, flower, or muppet sprites to be the same position as where Chipmunk says the virtual bodies are.

The key thing to understand about the above is Chipmunk-land is completely different than Cocos2D-land.

Bodies and Shapes

There’s one more thing you should understand before we dive into code: the concept of Chipmunk bodies and shapes.

A Chipmunk body represents an object in the Chipmunk virtual space. It can contain one or more Chipmunkshapes that represent the object’s geometry, as you can see below.

This picture shows the Chipmunk body we’ll be using to represent the cat bed. It has three Chipmunk shapes inside – one for the left side of the bed, one for the right side of the bed, and one for the bottom of the bed.

There are two kinds of Chipmunk bodies:

  • Dynamic bodies are bodies that can move – you’ll be using these most of the time.

  • Static bodies are bodies that never move – these are good to use for the ground in your game and other permanent fixtures.

For each Chipmunk body, you can specify how much mass it has. The more mass a shape has, the harder it is to move around and the heavier it becomes.

When you create shapes, you can specify whether they are boxes, circles, polygons, or segments (which are straight lines with a thickness). On each shape, you can set several properties, including the following:

  • elasticity: Represents how bouncy an object is. If you set this to 0, it’s not bouncy at all. If you set it to 1, it bounces back up with the same exact force it bounced down. If you set it higher to 1, it bounces away with an even higher force!

  • friction: Represents how slippery an object is. If you set this to 0, it’s extremely slippery. If you set this to 1 or higher, it’s not very slippery at all.

Overview the Sample Code of Cocos2d-x Chipmunk Test

This is the first time you’ve seen how to add objects to the Chipmunk scene, so let’s go through this section by section.

  • Create the walls to make sure objects don’t fall off the screen.

  • Adds the shape to the Chipmunk space.

  • Sets the touch event to add sprite when we touch screen.

The following project named ChipmunkTest in cocos2d-x samples.

Create Chipmunk space

This step is to create a virtual Chipmunk space to run the physics simulation in.

There’s an object that represents the Chipmunk space called cpSpace – you just need to create and initialize it.

Switch to header file(this case:ChipmunkTest.h) and make the following modifications:

// At top of file
#include "chipmunk.h"

// Inside @interface
cpSpace* m_pSpace;

Here you’re just importing the chipmunk header, and declaring an instance variable to keep track of the Chipmunk space, because you’ll be using it a lot!
Then switch to cpp(ChipmunkTest.cpp) and add the following modifications:

 void ChipmunkTestLayer::initPhysics()
{

#if CC_ENABLE_CHIPMUNK_INTEGRATION    
    // init chipmunk
    //cpInitChipmunk();

    m_pSpace = cpSpaceNew();

    m_pSpace->gravity = cpv(0, -100);

    // Physics debug layer
    m_pDebugLayer = CCPhysicsDebugNode::create(m_pSpace);
    this->addChild(m_pDebugLayer, Z_PHYSICS_DEBUG);
#endif
}

The first line calls cpSpaceNew to create a new object for the Chipmunk virtual space, and stores it in the space instance variable.
The second line sets the Chipmunk gravity to be nothing along the x-axis, and a decent amount down on the y-axis. As for what values to put here, it’s really a matter of tweaking to whatever “feels right” for your game.

Add “Wall”

For many games, it can be helpful to add objects to your Chipmunk space to represent the ‘Wall’.
For example, in this minigame we’re going to create a line segment shape from the bottom left to the bottom right. This way, when we create an object it will collide with the ground, rather than falling right off the screen!

To add the ground, make the following modifications to ChipmunkTestLayer::initPhysics():

    // rogue shapes
    // We have to free them manually
    //
    // bottom
    m_pWalls[0] = cpSegmentShapeNew( m_pSpace->staticBody,

        cpv(VisibleRect::leftBottom().x,VisibleRect::leftBottom().y),

        cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y), 0.0f);

    // top
    m_pWalls[1] = cpSegmentShapeNew( m_pSpace->staticBody, 

        cpv(VisibleRect::leftTop().x, VisibleRect::leftTop().y),

        cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f);

    // left
    m_pWalls[2] = cpSegmentShapeNew( m_pSpace->staticBody,

        cpv(VisibleRect::leftBottom().x,VisibleRect::leftBottom().y),

        cpv(VisibleRect::leftTop().x,VisibleRect::leftTop().y), 0.0f);

    // right
    m_pWalls[3] = cpSegmentShapeNew( m_pSpace->staticBody, 

        cpv(VisibleRect::rightBottom().x, VisibleRect::rightBottom().y),

        cpv(VisibleRect::rightTop().x, VisibleRect::rightTop().y), 0.0f);

    for( int i=0;i<4;i++) {

        m_pWalls[i]->e = 1.0f;

        m_pWalls[i]->u = 1.0f;

        cpSpaceAddStaticShape(m_pSpace, m_pWalls[i] );
    }

Add bodies/shapes

Next, we’re going to create a helper routine to add a dynamic (movable) Chipmunk body to the scene.

void ChipmunkTestLayer::addNewSpriteAtPosition(CCPoint pos)
{
#if CC_ENABLE_CHIPMUNK_INTEGRATION    
    int posx, posy;

    CCNode *parent = getChildByTag(kTagParentNode);

    posx = CCRANDOM_0_1() * 200.0f;

    posy = CCRANDOM_0_1() * 200.0f;

    posx = (posx % 4) * 85;

    posy = (posy % 3) * 121;

    int num = 4;

    cpVect verts[] = {

        cpv(-24,-54),

        cpv(-24, 54),

        cpv( 24, 54),

        cpv( 24,-54),
    };

    cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero));

    body->p = cpv(pos.x, pos.y);

    cpSpaceAddBody(m_pSpace, body);

    cpShape* shape = cpPolyShapeNew(body, num, verts, cpvzero);

    shape->e = 0.5f; shape->u = 0.5f;

    cpSpaceAddShape(m_pSpace, shape);

    CCPhysicsSprite *sprite = CCPhysicsSprite::createWithTexture(m_pSpriteTexture, CCRectMake(posx, posy, 85, 121));

    parent->addChild(sprite);

    sprite->setCPBody(body);

    sprite->setPosition(pos);

#endif

}

This should look pretty similar to step 3.

You’re just calling cpBodyNew to create a dynamic (movable) body when we touch the screen.

Set Touch Event

We need to add new body to perform when we touch the screen. I’ll show you the simplest possible way to do this now .

void ChipmunkTestLayer::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
    //Add a new body/atlas sprite at the touched location

    CCSetIterator it;

    CCTouch* touch;

    for( it = touches->begin(); it != touches->end(); it++) 
    {
        touch = (CCTouch*)(*it);

        if(!touch)

            break;

        CCPoint location = touch->getLocation();

        addNewSpriteAtPosition( location );
    }
}

We do here is call getLocation, which return the current touch location in Cocos2D coordinates.Finally,we call addNewSpriteAtPosition adding a sprite to position where you touched.

Compile and run

Compile and run! If all goes well, when you touch screen you should see bodes fall onto the ground , bounce a bit, and then settle down:

References

How To Create A Simple iPhone Game With Chipmunk Physics Tutorial

Addobjects.jpeg (6.9 kB) iven, 2013-02-22 07:50

BodiesandShapes.jpeg (8.5 kB) iven, 2013-02-22 07:51

final.png (65.1 kB) iven, 2013-02-22 07:51

forces.jpeg (7.7 kB) iven, 2013-02-22 07:51

update.jpeg (7.7 kB) iven, 2013-02-22 07:51

worldbased.jpeg (8.5 kB) iven, 2013-02-22 07:51

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.