![](/img/trans.png)
[英]Cocos2d - Is is possible to turn off collision for a Box2d b2Body with a b2FixtureDef?
[英]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.