2012-02-03 77 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)将精灵的左上角放在精灵的位置。

我的猜测是你的身体锚点位于身体的左下角,而精灵锚点位于右上角,给出了你所看到的效果。