2013-08-04 31 views
0

我在Box2d中创建了一个橡皮筋。这是我的代码。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形拉伸形式,然后将其逐渐开始收缩并来到水平笔直成为。任何人都可以告诉我为什么会发生?我希望橡皮筋在开始时不被拉伸。 最好的问候

回答

0

你不更新lastPos所以所有的身体最初占据相同的位置。 Box2D会迫使他们分开,这可能会导致问题。

+0

嗨,我正在改变它的价值像lastPos + = b2Vec2(宽度体,0)。你可以在上面的代码中看到它。我是否需要在其他地方更新它? – Aqueel

+0

嗨,我修复了我的代码。但现在还有另一个问题。你可以请这个线程? http://stackoverflow.com/questions/18042245/box2d-rubber-band-cant-throw-stone-with-its-torque – Aqueel

相关问题