Search code examples
cocos2d-iphone

Attaching two circles with a distance joint


I am using cocos2d along with box2d and I am trying to generate 2 circles which I did with this code

b2BodyDef bodyDef[2];
b2Body *body[2];

for (int i=0; i<=1; i++) 
{
    bodyDef[i].type = b2_dynamicBody;
    bodyDef[i].position.Set(((i+1)*blobSize)/PTM_RATIO,((i+1)*blobSize)/PTM_RATIO);
    body[i] = world->CreateBody(&bodyDef[i]);

    // Define another box shape for our dynamic body.
    b2CircleShape circle;
    circle.m_radius = (blobSize)/PTM_RATIO;

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &circle; 
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.4f;
    fixtureDef.restitution = 0.2f;
    body[i]->CreateFixture(&fixtureDef);
}

That code works flawlessly... then directly after that I put in my code for making the distance joint which looked like this

//Finding Midpoint of the circle
b2Vec2 blobCenter;
blobCenter.x = blobSize/2;
blobCenter.y = blobSize/2;

b2DistanceJointDef jointDef;

jointDef.Initialize(body[0], body[1],blobCenter, blobCenter);

jointDef.collideConnected = true;

This code compiles without errors however when executed the same thing occurs as before, just 2 cirlces are generated but they are not attached with a joint


Solution

  • The last 2 parameters of Initialize() specify the two anchor points of the joint in world coordinates, one on body0 and one on body1. I am not sure what you are trying to achieve with the vector blobCenter, but these two anchors (think of them as the 2 end points of the joint you are creating) technically shouldn't be the same.

    For a start, try:

    jointDef.Initialize(body[0], body[1], body[0]->GetWorldCenter(), body[1]->GetWorldCenter());
    

    This will set up a distance constraint = initial rest distance between the 2 bodies you created, and this distance will be maintained by the joint subsequently.

    And last but not least, add the joint to the world at the end of your code:

    world->CreateJoint(&jointDef);