Looping through ContactList - Only way to detect collisions?

Say, I have 3 bodies - A, B, C. I want to have a different action performed for each type of collision: A - B, B - C, C - A. In APE, you could set Collision Event Listeners for each body. When a collision event is fired, you could then retrieve the name of the body with which it has collided and carry out functions.

In Box2D, I could find only the following method:
Code:
for (var c: b2Contact = m_world.GetContactList() ; c ; c = c.GetNext())
{            
   // A positive manifold count ensures that the shapes are actually touching.
   if (c.GetManifoldCount() > 0)
   {
      var body1: b2Body = c.GetShape1().GetBody();
      var body2: b2Body = c.GetShape2().GetBody();
               
      if( (body1 == A || body2 == A) && (body1 == B || body2 == B) )
      {
                ...
      }

      if( (body1 == B || body2 == B) && (body1 == C || body2 == C) )
      {
                ...
      }
                  
      if( (body1 == C || body2 == C) && (body1 == A || body2 == A) )
      {
                ...
      }
   }
}         


Is that the only way to do it? Or is there an easier way? Isn't this process a little tedious for a large number of bodies?
In 1.4.3 there are no collision listeners like you might find in APE. This is different in the coming 2.0 release, but there is no saying how long it will be until that is ported to Flash.

b2World.GetContactList() gives the contacts for the entire world. There is also a function b2Body.GetContactList() that behaves the same, but only provides the contacts for that body. You will probably find that more convenient to use most of the time.

There is nothing to stop you in box2d setting up your own event listeners of course, which you may prefer if you have a large amount of unique collision code. Then in your main loop you'd just have something like:
Code:
for (var c: b2Contact = m_world.GetContactList() ; c ; c = c.GetNext())
{           
   // A positive manifold count ensures that the shapes are actually touching.
   if (c.GetManifoldCount() > 0)
   {
      var body1: b2Body = c.GetShape1().GetBody();
      var body2: b2Body = c.GetShape2().GetBody();
      body1.userData.onContact(body2,c);
      body2.userData.onContact(body1,c);
   }
} 

(or using the proper events framework)
Hey, thanks for the reply.

Using b2Body.getContactList() only gives the shapes touching within that b2Body, right? Or, does the contact list hold info about intersections of the current b2Body's shapes with any other b2Body's shapes?

About custom event listeners, I'm already using the userData variable to store the displayObject used to skin the body. Even otherwise, I don't understand your example. I would greatly appreciate a more elaborate explanation.

Thank you.
Anjan

edit: Fixed typo.
t_anjan wrote:
Using b2World.getContactList() only gives the shapes touching within that b2Body, right? Or, does the contact list hold info about intersections of the current b2Body's shapes with any other b2Body's shapes?

I presume you have a typo there, you must be asking about b2Body.getContactList. This contact list does inform you of all contacts between that body and another one. I.e. exactly one of c.GetShape1().GetBody() and c.GetShape2().GetBody() will be the original body. There is no such thing as contacts "within" a body; shapes inside the same body never collide.


t_anjan wrote:
About custom event listeners, I'm already using the userData variable to store the displayObject used to skin the body. Even otherwise, I don't understand your example. I would greatly appreciate a more elaborate explanation.


Sorry, I apologize, I'm still getting out of old school AS1/2 approach to events. Something a bit more appropriate for AS3 would be:
Code:
for (var c: b2Contact = m_world.GetContactList() ; c ; c = c.GetNext())
{           
   // A positive manifold count ensures that the shapes are actually touching.
   if (c.GetManifoldCount() > 0)
   {
      var body1: b2Body = c.GetShape1().GetBody();
      var body2: b2Body = c.GetShape2().GetBody();
      body1.userData.dispatchEvent( new b2ContactEvent(body2,c) );
      body2.userData.dispatchEvent( new b2ContactEvent(body1,c) );
   }
}


where you have written b2ContactEvent. This sends an event to each bodies userData. In your case (a very common one), your userData is a DisplayObject. This is ok, as you can still dispatch events to these. You'd then use body.addEventListener to catch these events, which is presumeably very similar to what you'd have to do in APE.
There's a post where I talk about how I do this here. I have since fixed some bugs, so I would like to post some code here in case anyone wants to use it or look at it to make their own system.

I didn't use AS3 events because I wasn't sure about performance. I think the way I have programmed it is fairly efficient, but I haven't really done any stress testing. I've had 100s of shapes colliding, but I don't have tons of different groups or anything. This code is for my collision trigger system and my group system. I am storing a custom class in the userData which I call GameShape. It holds the graphics and the group information that is used for collisions.

Just a little disclaimer on the code: It's not finished! It works fine for me, but doesn't have all the features I hope to add eventually. It's also not amazingly organized, and naming conventions are probably totally crazy. It's just a small part of a game engine I've been writing over the past ~2 months that totals over 350KB of code. So if you use it in a game/etc.. and it explodes I'm not responsible. It's meant more for looking at to make your own system, but you could probably drop it into your game with a few modifications (you'd need userData to store a GroupList for one).
Hey, thanks to both of you. I will post back if I have any more doubts.

Thanks, again!

edit: The b2ContactEvent class needs to be created by me, right? Is there any specific reason why the event has to be dispatched by the userData and not by the body itself?

And, for the body to be able to listen for events, the b2Body class needs to extend EventDispatcher class, right?
And, here comes another question:

I'm using the vehicle from the testbed example: TestExample.as. It has a belt around it's wheels. The belt is made up of multiple small rectangles (each rectangle is a separate body) joined together by RevoluteJoints.

Now, if I need to detect other bodies colliding with this vehicle, do I need to attach EventListeners to each of the belt's individual bodies? There are about 30 of these small bodies in my code. And the current logic uses the same variable to create these bodies in a loop.

Is there any method of assigning all these bodies to a "group" and assign just one event listener to this group?
Here's my logic for sending events to userData. b2Bodies are "inside" the box2d engine, and so shoudn't really be tampered with just to implement your own game logic. They are not event listener descendants, so you cannot dispatch events to them without modificaion. userData is the appropriate place for storing game logic. You've already got a system where you use userData to point to a display object which is convenient, as these do extend EventDispatcher.

It's a simple system, which means you will experience problems like having to set a lot of listeners, but you should be able to put them in systematically. A way to speed up the process, if you don't mind mixing your display logic and game logic, is to add the event listeners in the constructors for the display objects. You don't have to explicity check (body2==chain1)||(body==chain2)..., you can reuse the collision masks / type data / custom fields.
E.g. (body2.userData instanceof MyChainGraphic) or body2.userData.isEnemy.

Once you start wanting more advanced behaviour than that, particularly custom "groups" as you were describing, it's best to have a game object in the userdata, that keeps track of that sort of thing and applies it's own functionality. This game object stores a reference to it's DisplayObject (or Bitmap or whatever), separating game logic from display logic. brainclogs code is a great example of that, his GameShape being the class to put in userData.
Yes, as BorisTheBrave said, I am storing my GameShape objects in the userData. I'm not actually using AS3 events for the code. So you actually can make a bunch of shapes/bodies that all belong to a group and just set one trigger (it's like an event) for that group type to do something when it hits another group type. I realize that I should have included a little more about actions, and some explanation of how you add triggers. So I have updated the code with 2 more files. One is an example action, and the other is the ICollisionAction class, both of which are very small. There is also more explanation in the TriggerManager comments and in the example action. Here is how you would create a trigger:

Code:
   var monkeyeatbanana:ICollisionAction = new MonkeyEatBanana();
   TriggerManager.getInstance().addCollisionTrigger("Monkey","Banana",monkeyeatbanana);


If you had a million monkeys and a million bananas flying around on the screen, you would only add this trigger once and you would have a bunch of very happy digital monkeys flying around your screen 😛

You would have to create an action that implements ICollisionAction though, which basically just has to implement a "run" function. This takes the collision information and does whatever you tell it to do with it. So the trigger will call this action whenever two shapes where one shape belongs to group "Monkey" and one belongs to "Banana". Then you can check which shape is the Banana and get rid of it probably, and get the GameShape for monkey and you would have some sort of "Actor" object that would hold variables like his health, hunger, etc... Then you could make him a happier monkey because he has the banana.

If you want a more generic action, like to damage an enemy, you could make the action constructor take a group name as in the included ExampleAction. That name would be the group of the projectile probably. Then you could check which shape is which, and the object that doesn't belong to the projectile group gets damaged and the projectile disappears.

Hopefully this makes a little more sense now. BTW files have been updated in my original post.
Hey, thanks for all the help guys.

If I'm going to use userData as a receiver of events, then that means every body in the game should have a displayObject userData. But, I currently have only some bodies that have a userData defined. That is why I extended b2Body from EventDispatcher.

I'll be back with more questions. 😀

Original thread: https://box2d.org/forum/viewtopic.php?t=450