0

I have 3 box2d bodies. All of them have user data. Their userData's tags are shown below.

BODY 1: Tag = 1
BODY 2: Tag = 1
BODY 3: Tag = 2

Further in my code, I have implemented contact listener to detect contacts between bodies and I have put condition that Body 3 will be destroyed either collision between BODY1 and BODY3 or BODY2 and BODY3

But when BODY1 and BODY2 collide with BODY3 at the same time, I am getting EXC_BAD_ACCESS. I know why this error appears : it is because there is no body to remove, as it is removed at first contact.

Anyone know how I can solve this error?

4

1 回答 1

1

您可以设置一个条件来检查您的碰撞体是否 == NULL。

如果不是,就销毁它。如果是,那就是它已经被摧毁了。

编辑 :

要保留您的特定标签系统,您可以将 NSDictionary 作为每个 body 的用户数据传递:

bodyDef.userData = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithInt:theBodyTag], @"tag",
                             [NSNumber numberWithInt:theUniqueID], @"ID", 
                             nil];

然后,当发生碰撞时,您可以检查身体用户数据并知道您是否在身体 3 中。

if ([(id)body1->GetUserData() objectForKey:@"ID"] == 3) {
        if ([(id)body2->GetUserData() objectForKey:@"ID"] == 1 || 
            [(id)body2->GetUserData() objectForKey:@"ID"] == 2) {
                Feed an array with the body to destroy and destroy it after your collision checks !
                [myQueue addObject:[(id)body2->GetUserData() objectForKey:@"ID"]];
        }
}

在碰撞例程之后,遍历所有身体并销毁将队列对象作为唯一 ID 的身体。

请注意,我实际上并没有检查此代码是否有效,但这就是想法。

于 2013-06-18T11:25:41.093 回答