0

我正在 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形拉伸形式出现,然后逐渐开始收缩并水平变直。谁能告诉我为什么会这样?我希望橡皮筋在开始时不会被拉伸。此致

4

1 回答 1

0

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

于 2013-08-04T07:34:32.247 回答