这就是我将自己的身体从世界中移除的方式:_world->DestroyBody(spriteBody);
在我的游戏中,我不断创建Cocos2d Sprite和Box2D Body,我也不断删除它们。
然而,当我尝试LOG("%d", _world->GetBodyCount());
时,这个数字会增加而且永远不会减少。
我认为_world->DestroyBody(spriteBody);
可能无法完全删除我的Box2D正文。
这是我的删除方法。
void GameScene::deleteSprite(Sprite *sprite){
b2Body *spriteBody = NULL;
for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
Sprite *curSprite = (Sprite *)b->GetUserData();
if (sprite == curSprite) {
log("3");
spriteBody = b;
break;
}
}
}
if (spriteBody != NULL) {
//spriteBody->SetUserData(NULL);
//b2Fixture* f = spriteBody->GetFixtureList();
//spriteBody->DestroyFixture(f);
spriteBody->GetWorld()->DestroyBody(spriteBody);
}
sprite->removeFromParentAndCleanup(true);
}
创建方法 - 我从GMTDev和Raywenderlich获取此代码。 Box2D仅用于碰撞检测
void GameScene::addBoxBodyForSprite( Sprite *sprite, int iNumVerts, b2Vec2 verts[] ){
if( _world==NULL )
return;
Point pos = sprite->getPosition();
Size size = sprite->getContentSize();
b2BodyDef spriteBodyDef;
spriteBodyDef.type = b2_dynamicBody;
spriteBodyDef.position.Set(pos.x/PTM_RATIO, pos.y/PTM_RATIO);
spriteBodyDef.userData = sprite;
b2Body *spriteBody = _world->CreateBody(&spriteBodyDef);
b2PolygonShape spriteShape;
if( iNumVerts!=0 )
{
spriteShape.Set(verts, iNumVerts);
b2FixtureDef spriteShapeDef;
spriteShapeDef.shape = &spriteShape;
spriteShapeDef.density = 10.0;
spriteShapeDef.isSensor = true;
spriteBody->CreateFixture(&spriteShapeDef);
}
else
{
// No Vertice supplied so just make a box round the sprite
b2BodyDef spriteBodyDef;
spriteBodyDef.type = b2_dynamicBody;
spriteBodyDef.position.Set( pos.x/PTM_RATIO, pos.y/PTM_RATIO );
spriteBodyDef.userData = sprite;
b2Body *spriteBody = _world->CreateBody( &spriteBodyDef );
b2PolygonShape spriteShape;
spriteShape.SetAsBox( size.width/PTM_RATIO/2, size.height/PTM_RATIO/2 );
b2FixtureDef spriteShapeDef;
spriteShapeDef.shape = &spriteShape;
spriteShapeDef.density = 10.0;
spriteShapeDef.isSensor = true; // isSensor true when you want to know when objects will collide without triggering a box2d collision response
spriteBody->CreateFixture( &spriteShapeDef );
}
}
谢谢!
答案 0 :(得分:0)
问题是在@UmeshSharma和@ LearnCocos2D
的帮助下解决的 我从GMTDev获取的create方法中的有一些错误,其中函数_world-> CreateBody被使用了两次(当iNumVerts == 0时)
因此,当我删除我的身体和精灵。实际上还有另一个身体用于该精灵。然后它崩溃了Box2D机身找不到它的Cocos2d精灵的更新。