iBrad Apps iBrad Apps - 1 month ago 17
iOS Question

Box2D collision detection issue?

I am using a very simple b2ContactListener. However when my objects collide, there are multiple callbacks for one collision physically. Is there any way to modify this or add some checks so that there will be only one callbacks for one collision physically? I have been struggling with this for weeks and I just can't seem to figure this out :(

Can anyone offer any tips or suggestions?

Thanks!

Answer

I use a bool flag on my objects for this.

When a contact is fired:

if the flag is set already = just ignore else set the flag and add the object to the doSomethingNowWithThis list.

This way only one contact sets the flag, and the rest are ignored. Prevents me from over-removing.

There might be a better way, but this works for me.

Example using levelhelper in iOS.

   //I register a laser to hit the roof
   [lh registerBeginOrEndCollisionCallbackBetweenTagA:PLAYERFIRE 
                                               andTagB:ROOF 
                                            idListener:self 
                                           selListener:@selector(flagPartAToDie:)];

    //Then it calls this
   -(void)flagPartAToDie:(LHContactInfo*)contact {
    MyUserData* myud;
    LHSprite* part = [contact spriteA];
    myud = (MyUserData*) part.userData;
    if (!myud.DeleteMe) {
        myud.DeleteMe = YES;
        [deadParts addObject: part];            
    }    
 }
Comments