checking for and reacting to collisions between fixtures

Topics: User Forum
Feb 24, 2011 at 4:25 AM

Hi guys, I'm having a hard time understanding how to do this.  I have lists of different types of objects, like Props, Agents, Projectiles, etc.  Each of these objects has a Fixture associated with it, and they all share the same World.  They have working CollisionCategories set up as well.  Now I need to check, every frame, whether a collision has occurred between _any_ Projectile and _any_ Agent / Prop, so that I can do stuff like remove the Projectile, hurt the Agent / Prop that was hit, spawn particle effects at the point of impact, et cetra.

What is the best way for me to do this?  Do I need to manually check every Projectile against every Agent / Prop?  How, exactly?  With nested foreach loops through each list of each type?  (hopefully not!)  Can I somehow just ask the Projectile's fixture each frame if it collided with anything in the world, then get some kind of reference to the hit object?  

Thanks for your time and for any help you can offer!  :)

Feb 24, 2011 at 11:19 AM
Edited Feb 24, 2011 at 1:37 PM

Yes, you can hook to the OnCollision event of your Body (FarseerPhysics.Dynamics.Body):

Body.OnCollision += Body_OnCollision; // or use a lambda

// ...

bool Body_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
{
    // fixtureA: The fixture of 'Body'
    // fixtureB: The fixture of the body that collided with 'Body'
    // return true : acknowledge the collision
    // return false : ignore the collision the collision
}

There is also another event called 'OnSeparation' should you need that.

Feb 24, 2011 at 4:46 PM
Edited Feb 24, 2011 at 4:53 PM

Alright, now I understand!  Thank you so much for your time, I can't tell you how much I appreciate that..  I wasn't understanding how hooks/subscriptions work. 

EDIT:
It seems I've figured out how to do this after all...  Thanks again for your help!

Now the issue I'm having is how to set UserData to something useful.  The way I've got things set up is, I have different classes of objects, and each object class has a Fixture+Body as a member.  The most useful thing I could set UserData to would be a reference to that Fixture's parent Entity.  Possibly with mFixture.UserData = this;

Then I could do something like this inside the method you gave me:

 

if (fixtureB.UserData represents_a PropEntity_instance)
{
That_PropEntity_instance.ReactToCollision();
}

 

I've found a couple of pages that talk about how to do this, but I don't understand how it's supposed to give me an instance to use.  I'm going to be using 100% trial and error to figure out a working implementation, so if anyone reading this can advise me on a good way to do this, I would very much appreciate it.

Thanks!