Home > iPhone Development > Distance Joint of Box2D

Distance Joint of Box2D

In this article, I will present how to create a distance joint with Box2D. The example in my last article How to Use DebugDraw of Box2d with Cocos2d is used as the basis. A box is added to the world, and a distance joint between the box and ball will be created.

Step 1: Create a box in the physics world. (in the initialization method)

b2BodyDef boxBodyDef;
	boxBodyDef.position.Set(200.0f/PTM_RATIO, 400.0f/PTM_RATIO);
	boxBody = world->CreateBody(&boxBodyDef);
	b2PolygonDef boxShapeDef;
	boxShapeDef.SetAsBox(50.0f/PTM_RATIO/2, 50.0f/PTM_RATIO/2);
	boxShapeDef.density = 1.0f;
	boxShapeDef.friction = 0.3f;
	boxShapeDef.restitution = 0.5f;
	boxBody->CreateFixture(&boxShapeDef);
	boxBody->SetMassFromShapes();

Step 2: Create a distance joint between the box and ball. (in the initialization method)

b2DistanceJointDef dj;
	dj.Initialize(ballBody, boxBody, ballBody->GetPosition(),boxBody->GetPosition());
	dj.collideConnected = true;
	m_distanceJoint = (b2DistanceJoint*) world->CreateJoint(&dj);

Note: the attribute collideConnected determines if the box and the ball collide. If the valie is false, the box and ball will overlap.

All done!

——————————–

Download: You can download the source codes from here.

Categories: iPhone Development
  1. August 12th, 2009 at 21:46 | #1

    Awesome! Thanks so much for thee tutorials. Box2d is intimidating to work with and your info is making it much more approachable!

  1. No trackbacks yet.