Box2d:弹性绳索需要时间才能回到初始位置

时间:2013-08-04 02:57:45

标签: objective-c cocos2d-iphone box2d-iphone rubber-band

我正在Box2d中创建一个橡皮筋。这是我的代码。

// init physics
    [self initPhysics];

    // Create ball body

    CCSprite *ball = [CCSprite spriteWithFile:@"rubberband.png"];
    ball.position = ccp(100, 100);
    ball.tag = 1;
   // [self addChild:ball];

    //=======Params
    // Position and size
    b2Vec2 lastPos = b2Vec2(154.0/PTM_RATIO,65.0/PTM_RATIO); //set position first body
    float widthBody = 2.0/PTM_RATIO;
    float heightBody = 2.0/PTM_RATIO;
    // Body params
    float density = 0.0;
    float restitution = 0.5;
    float friction = 0.5;
    // Distance joint
    float dampingRatio = 0.85;
    float frequencyHz = 10;
    // Rope joint
    float kMaxWidth = 50.0/PTM_RATIO;
    // Bodies
    int countBodyInChain = 68;
    b2Body* prevBody;
    //========Create bodies and joints
    for (int k = 0; k < countBodyInChain; k++) {
        b2BodyDef bodyDef;
        if(k==0 || k==countBodyInChain-1) bodyDef.type = b2_staticBody; //first and last bodies are static
        else bodyDef.type = b2_dynamicBody;
        bodyDef.position = lastPos;

        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);

        if(k>0) {
            b2RevoluteJointDef armJointDef;
                        armJointDef.Initialize(prevBody, body, lastPos);
                        armJointDef.enableMotor = true;
            armJointDef.enableLimit = true;
                        armJointDef.maxMotorTorque = 1;
            world->CreateJoint(&armJointDef);

            //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;
            rDef.collideConnected = false;

            world->CreateJoint(&rDef);

        } //if k>0
        lastPos += b2Vec2(widthBody, 0); //modify b2Vect for next body
        prevBody = body;
    } //for -loop


[self scheduleUpdate];
}
return self;

}

问题是,当应用程序启动时,橡皮筋以U形状呈拉伸形式,然后逐渐开始收缩并变为水平直线。谁能告诉我为什么会这样?我希望橡皮筋在开始时不被拉伸。 最诚挚的问候

1 个答案:

答案 0 :(得分:0)

您不更新lastPos,因此所有实体最初都占据相同的位置。 Box2D将迫使它们分开,这可能导致问题。