Box2d弹力绳接头

Gra*_*lex 4 box2d-iphone

我正在写一个游戏,我需要编一根绳子.我用b2RopeJoint做了它,但在那里我没有找到机会让它变得有弹性.然后我寻找b2DistanceJoint,一切都很酷,有弹性,但我找不到能力设置一个限制只有最大距离(没有最小距离).

我该怎么做?

Sin*_*nba 5

试试这个.

-(void) CreateElasticRope {
    //=======Params
    // Position and size
    b2Vec2 lastPos = b2Vec2(4,4); //set position first body
    float widthBody = 0.35;
    float heightBody = 0.1;
    // Body params
    float density = 0.05;
    float restitution = 0.5;
    float friction = 0.5;
    // Distance joint
    float dampingRatio = 0.0;
    float frequencyHz = 0;
    // Rope joint
    float kMaxWidth = 1.1;
    // Bodies
    int countBodyInChain = 15;
    b2Body* prevBody;

    //========Create bodies and joints
    for (int k = 0; k < countBodyInChain; k++) {
        b2BodyDef bodyDef;
        if(k==0 ) bodyDef.type = b2_staticBody; //first body is static
        else bodyDef.type = b2_dynamicBody;
        bodyDef.position = lastPos;
        lastPos += b2Vec2(2*widthBody, 0); //modify b2Vect for next body
        bodyDef.fixedRotation = YES;
        b2Body* body = world->CreateBody(&bodyDef);

        b2PolygonShape distBodyBox; 
        distBodyBox.SetAsBox(widthBody, heightBody);
        b2FixtureDef fixDef;
        fixDef.density = density;
        fixDef.restitution = restitution;
        fixDef.friction = friction;
        fixDef.shape = &distBodyBox;
        body->CreateFixture(&fixDef);
        body->SetHealth(9999999);
        body->SetLinearDamping(0.0005f);

        if(k>0) {
            //Create distance joint
            b2DistanceJointDef distJDef;
            b2Vec2 anchor1 = prevBody->GetWorldCenter();
            b2Vec2 anchor2 = body->GetWorldCenter();
            distJDef.Initialize(prevBody, body, anchor1, anchor2);
            distJDef.collideConnected = false;
            distJDef.dampingRatio = dampingRatio;
            distJDef.frequencyHz = frequencyHz;
            world->CreateJoint(&distJDef);

            //Create rope joint
            b2RopeJointDef rDef;
            rDef.maxLength = (body->GetPosition() - prevBody->GetPosition()).Length() * kMaxWidth;
            rDef.localAnchorA = rDef.localAnchorB = b2Vec2_zero;
            rDef.bodyA = prevBody;
            rDef.bodyB = body;
            world->CreateJoint(&rDef);

        } //if k>0
        prevBody = body;
    } //for 
}
Run Code Online (Sandbox Code Playgroud)