Introduction
In this brief article we’ll be taking a look at an efficient way of creating ropes in our cocos2d games that use box2d, starting from a cocos2s+box2d template project.
We will be using box2d’s latest addition, the b2RopeJoint to constrict two bodies with a rope joint (a maximum distance joint, one might also call it), so as always big thanks to Erin Catto for all his hard work on box2d.
We will also be using a small set of classes I wrote, VRope, that use Verlet integration to calculate the points of the rope, using a CCSpriteBatchNode to visually draw the rope in our game.
It’s worth mentioning that using Box2D isn’t strictly necessary, you could still use the VRope class to draw a rope between two given points in other scenarios (for example using Chipmunk, your own physics system, or simply updating the two points manually) and have it react under gravity. With that in mind, the class also has some helper methods to use it with CGPoints only. (somethingWithPoints methods)
Setting up the project
First things first, make sure you have the latest version of Cocos2D and create a new project with the “Cocos2d Box2d Application” template. You will then need to update Box2D to the latest committed version, which you can find at http://code.google.com/p/box2d/source/checkout
To update Box2D in your current project:
- From within XCode, delete the Box2D folder group from the “cocos2d Sources” folder (Delete References)
- From Finder, go to your project’s folder and delete the Box2D folder
- Copy over the latest version of Box2D back into your project’s folder (make sure you only copy the most deep rooted “Box2D” folder, and delete CMakeLists.txt and Box2DConfig.cmake)
- Back to XCode, Project -> Add to Project, select the Box2D folder, make sure create groups (not folder reference) is selected, Add
This should give you a working Cocos2D project, updated with the latest Box2D source that has the b2RopeJoint ready to use.
If you’re not running the latest version of cocos2d (0.99.5-rc0) but still want to use VRope, you’ll need to rename CCSpriteBatchNode back to CCSpriteSheet, the rest should work as is.
Using b2RopeJoint
Using the new b2RopeJoint is very easy, it’s similar to the b2DistanceJoint, but unlike other joints it doesn’t have an Initialize method.
//define rope joint, params: two b2bodies, two local anchor points, length of rope b2RopeJointDef jd; jd.bodyA=body1; //define bodies jd.bodyB=body2; jd.localAnchorA = b2Vec2(0,0); //define anchors jd.localAnchorB = b2Vec2(0,0); jd.maxLength= (body2->GetPosition() - body1->GetPosition()).Length(); //define max length of joint = current distance between bodies world->CreateJoint(&jd); //create joint







Recent Comments