繁体   English   中英

正确删除Box2D固定装置并更新b2Body

[英]Correctly removing Box2D fixtures and updating b2Body

我有一个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());

这条线看起来可疑。

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

子画面的锚点通常为(0.5,0.5)。 如果您身体的锚点位于中间(根据上面的代码无法分辨),则精灵的锚点(0.5,0.5)也会将其也置于中间。 将其放在(0,0)会将小精灵的左上角放在小精灵的位置。

我的猜测是您的身体锚位于身体的左下角,而精灵锚位于右上角,从而产生您所看到的效果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM