【问题标题】:Correctly removing Box2D fixtures and updating b2Body正确移除 Box2D 固定装置并更新 b2Body
【发布时间】:2012-02-03 11:32:15
【问题描述】:

我有一个 Box2d 身体,我正试图将其分成多个部分。为此,我迭代了它的固定装置并为每个固定装置生成新的主体。使用调试绘图,我可以看到这似乎有效。

正如您在上图中所见,主要主体正在被破坏,并且正在生成辅助主体(标记为: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());

【问题讨论】:

    标签: iphone cocos2d-iphone box2d box2d-iphone


    【解决方案1】:

    这条线看起来很可疑。

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

    精灵的锚点通常为 (0.5,0.5)。如果你的身体的锚点在中间(不能从上面的代码中看出),那么精灵的锚点(0.5,0.5)也会把它放在中间。将它放在 (0,0) 处会将精灵的左上角放在精灵的位置。

    我的猜测是你的 body 锚点在 body 的左下角,而 sprite 锚点在右上角,给出了你所看到的效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-29
      • 1970-01-01
      • 2011-04-29
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      相关资源
      最近更新 更多