使用旋轉連接器實現鏈條效果

void WorldLayerSence::createLineRouteJoint(
    b2World* world,b2Body* body )
{
    CCSprite* sprit = CCSprite::create("link.png");
    sprit->setPosition(ccp(160,230));
    addChild(sprit);
    //鏈條節點
    b2BodyDef def;
    def.userData = sprit;
    def.type = b2_staticBody;
    //第一個節點做成靜態剛體用以固定他的位置
    def.position.Set(160/PTM_RATIO,230/PTM_RATIO);
    b2FixtureDef fixdef;
    fixdef.density = 1;//密度
    fixdef.restitution = 0.9;//反彈係數
    fixdef.friction = 1;//摩擦力
    b2PolygonShape shap;
    shap.SetAsBox(
        sprit->getContentSize().width/2/PTM_RATIO,
        sprit->getContentSize().height/2/PTM_RATIO);
    fixdef.shape= &shap;
    b2Body* linkNodeBody = world->CreateBody(&def);
    linkNodeBody->CreateFixture(&fixdef);
    //使用循環創建15個鏈條節點
    for(int i = 0; i<15; i++)
    {
        def.type = b2_dynamicBody;
        CCSprite* sp = CCSprite::create("link.png");
        sprit->setPosition(ccp(160,230));
        addChild(sp);
        def.userData = sp;
        b2Body* newLinkNodeBody  = world->CreateBody(
                                       &def);
        newLinkNodeBody->CreateFixture(&fixdef);
        //針對兩節節點創建關節
        createNodeRouteJoint(world,linkNodeBody,
                             newLinkNodeBody);
        linkNodeBody = newLinkNodeBody;
    }
};
void WorldLayerSence::createNodeRouteJoint(
    b2World* world,b2Body* node,b2Body* newNode)
{
    //創建旋轉關節
    b2RevoluteJointDef revoluteJointDef;
    revoluteJointDef.localAnchorA.Set( 0,-0.5);
    revoluteJointDef.localAnchorB.Set(0,0.5);
    //inside the loop, only need to change the bodies to be joined
    revoluteJointDef.bodyA = node;
    revoluteJointDef.bodyB = newNode;
    revoluteJointDef.collideConnected = false;
    revoluteJointDef.enableLimit = false;
    m_world->CreateJoint( &revoluteJointDef );
}
發佈了34 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章