2012-02-03 56 views
2

我有一個Box2d機構,我試圖分成多個部分。要做到這一點,我遍歷它的燈具,併爲每個生成新的機構。使用調試繪製,我可以看到這似乎工作。正確刪除Box2D燈具和更新b2Body

enter image description here

正如你可以在上述圖像中所看到的,主本體被打破和次級體(標記爲:2)被生成。基於調試層的形狀呈現,它們被正確表示。我遇到的問題是,與我的主要b2body關聯的CCSprite沒有正確定位以引用新的主體。看起來好像關聯的CCSprite被定位(給定一個0,0的錨點),就好像它仍然是一個更大形狀的一部分。

僅供參考,這裏是我使用的代碼:

for (b2Fixture *f = body->GetFixtureList(); f; f = f->GetNext()) 
{ 
    NSString *newSpriteFrameName = (NSString *)f->GetUserData(); 

    // Steal some of our parent bodies properties 
    b2BodyDef bd; 
    bd.type = b2_dynamicBody; 
    bd.position = [self physicsPosition]; 
    bd.angle = [self angle]; 

    b2Body *newBody = _world->CreateBody(&bd); 

    b2FixtureDef fixtureDef; 
    fixtureDef.shape = f->GetShape(); 
    fixtureDef.density = f->GetDensity(); 
    fixtureDef.restitution = f->GetRestitution(); 
    fixtureDef.friction = f->GetFriction(); 
    fixtureDef.userData = f->GetUserData(); 
    newBody->CreateFixture(&fixtureDef); 

    // Try to transfer any angular and linear velocity 
    b2Vec2 center1 = [self worldCenter]; 
    b2Vec2 center2 = newBody->GetWorldCenter(); 

    CGFloat angularVelocity = parentBody->GetAngularVelocity(); 
    b2Vec2 velocity1 = [self linearVelocity] + b2Cross(angularVelocity, center1 - center1); 
    b2Vec2 velocity2 = [self linearVelocity] + b2Cross(angularVelocity, center2 - center1); 

    newBody->SetAngularVelocity(angularVelocity); 
    newBody->SetLinearVelocity(velocity2); 

    // Create a new destructable entity 
    CCSprite *newSprite = [CCSprite spriteWithSpriteFrameName:newSpriteFrameName]; 
    SIDestructableEntity *newEntity = [[SIDestructableEntity alloc] initWithBody:newBody node:newSprite]; 
    [[newEntity ccNode] setAnchorPoint:CGPointMake(0, 0)]; 
    [game.entities addObject:newEntity]; 
    [game.entityLayer addChild:[newEntity ccNode]]; 
} 

下面是我如何設置我的CCSprites位置的每個邏輯滴答:

b2Vec2 position = body->GetPosition(); 
ccNode.position = CGPointMake(PTM_RATIO*position.x, PTM_RATIO*position.y); 
ccNode.rotation = -1 * CC_RADIANS_TO_DEGREES(body->GetAngle()); 

回答

0

這行看起來可疑。

[[newEntity ccNode] setAnchorPoint:CGPointMake(0, 0)]; 

精靈通常具有(0.5,0.5)的定位點。如果你的身體的錨點位於中間(不能從上面的代碼中看出),那麼精靈的錨點(0.5,0.5)也會將它放在中間。將它放在(0,0)將精靈的左上角放在精靈的位置。

我的猜測是你的身體錨點位於身體的左下角,而精靈錨點位於右上角,給出了你所看到的效果。