cocos2d-x 物理引擎Box2D 連接器之距離連接器

直接上代碼

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);
    //創建距離連接器
}

發佈了34 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章