直接上代码
void WorldLayerSence::createDistanceJoint(
b2World* world,const char* name)
{
CCSize size =
CCDirector::sharedDirector()->getVisibleSize();
//1、创建一个刚体
CCSprite* sprite1 = CCSprite::create(name);
sprite1->setPosition(ccp(70,240));
addChild(sprite1);
b2BodyDef def;
def.type = b2_dynamicBody;
def.position.Set(70/PTM_RATIO,240/PTM_RATIO);
def.userData=sprite1;
b2Body* body1 = m_world->CreateBody(&def);
b2PolygonShape shap;
shap.SetAsBox(
sprite1->getContentSize().width/2/PTM_RATIO,
sprite1->getContentSize().height/2/PTM_RATIO);
b2FixtureDef fixdef;
fixdef.shape = &shap;
fixdef.density = 1;//密度
fixdef.friction = 1; //摩擦系数
fixdef.restitution=1.2; //弹力系数
body1->CreateFixture(&fixdef);
//2、创建第二个刚体
CCSprite* sprite2 =
CCSprite::create("blackbull.png");
sprite2->setPosition(ccp(220,200));
addChild(sprite2);
def.type = b2_dynamicBody;
def.position.Set(220/PTM_RATIO,200/PTM_RATIO);
def.userData = sprite2;
b2Body* body2 = m_world->CreateBody(&def);
b2PolygonShape shap2;
shap2.SetAsBox(
sprite2->getContentSize().width/2/PTM_RATIO,
sprite2->getContentSize().height/2/PTM_RATIO);
fixdef.shape=&shap2;
fixdef.density=1;
fixdef.friction=1;
fixdef.restitution=0.9;
body2->CreateFixture(&fixdef);
//创建距离连接
b2DistanceJointDef disdef;
disdef.collideConnected = true;
disdef.frequencyHz = 30.0f; //频率
disdef.dampingRatio = 1.0f; //阻尼率
disdef.Initialize(body2,body1,
body2->GetWorldCenter(),body1->GetWorldCenter());
//设置两个刚体和他们的距离连接器的锚点
m_world->CreateJoint(&disdef);
//创建距离连接器
}