0
我有一個奇怪的問題。我的球員的射門,當它與身體相撞時,會毫無問題地將其摧毀,但是當它同時擊中兩個身體時,它會崩潰。身體之間的奇怪聯繫
射擊選手
b2Body *shooting = [_lhelper newBodyWithUniqueName:@"shoot" world:_world];
CCSprite *shootingSprite = (CCSprite *)shootingBody->GetUserData();
shootingBody.position = pos;
shootingBody->SetTransform(b2Vec2(pos.x/PTM_RATIO,
pos.y/PTM_RATIO),
CC_DEGREES_TO_RADIANS(angle));
接觸
if([spriteA tag] == ENEMY && [spriteB tag] == SHOT)
{
int animIdx = [(NSNumber*)[spriteA userData] intValue];
if(animIdx < 2)
{
[spriteA setTextureRect:MY_RECTS[animIdx]];
[spriteA setUserData:[NSNumber numberWithInt:animIdx+1]];
}
else
{
[objectThatWillBeDeleted addObject:[NSValue valueWithPointer:bodyA]];
}
[objectThatWillBeDeleted addObject:[NSValue valueWithPointer:bodyB]];
}
else if([spriteB tag] == ENEMY && [spriteA tag] == SHOT)
{
int animIdx = [(NSNumber*)[spriteB userData] intValue];
if(animIdx < 2)
{
[spriteB setTextureRect:MY_RECTS[animIdx]];
[spriteA setUserData:[NSNumber numberWithInt:animIdx+1]];
}
else
{
[objectThatWillBeDeleted addObject:[NSValue valueWithPointer:bodyB]];
}
[objectThatWillBeDeleted addObject:[NSValue valueWithPointer:bodyA]];
}
更新
std::vector<Contact>::iterator pos;
for(pos = _contactListener->_contacts.begin();
pos != _contactListener->_contacts.end(); ++pos)
{
Contact contact = *pos;
//[self checkBodies2:&contact];
}
for(NSValue* val in objectThatWillBeDeleted)
{
b2Body* body = (b2Body*)[val pointerValue];
[_lhelper removeBody:body];
}
[objectThatWillBeDeleted removeAllObjects];
}
}
我不明白的地方的錯誤。
謝謝。嘗試去做 – user1007760
如果碰撞接觸同時接觸兩個物體,則會爲同一個身體報告兩次碰撞接觸。這是正常的行爲。您應該使用NSMutableSet來確保objectThatWillBeDeleted中只能存在一個類型的一個對象。在添加它之前,您可能必須查詢NSMutableSet是否存在該主體。請參閱:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsmutableset_Class/Reference/NSMutableSet.html – LearnCocos2D