Thursday, January 17, 2008

Box2DFlashAS3 : Detecting Jack-in-the-Box Collisions

In my last post we started looking at the basics of using Box2DFlashAS3. We saw that you needed to listen for enterFrame events and use this event to update the position of the Sprites representing your Physics Bodies. This post I want to consider how you'd deal with special cases. For example, when you have a Body that needs to respond to a collision in a unique way. Imagine a ball falling onto a Jack-in-the-Box and triggering the box to spring open. The ball will be thrown up and to one side. This sort of response can't be represented by manipulating the elasticity of the two Bodies. The question is how would you detect and respond to the ball colliding with these bodies.

Our Jack-in-the-Box simulation has one special object: the ball. We want to take action when the ball collides with a special object (i.e the Jack-in-the-Box). The ball is a standard b2Body and it maintains a list of what it is in contact with. You can access this list using ball.GetContactList() to return a b2ContactNode. The first body in the list can be accessed using b2ContactNode's "other" property (I assume you can move through the list of contacts using "next" and "prev" but I haven't needed to test this yet). You can then check if this is a b2Body that needs a response. For example, if we have a b2Body called jack we could check if it is in contact with our ball like this :

var c_ball:b2ContactNode = this.ball.GetContactList();
var o_contact:b2Body = c_ball.other;

if(this.jack == o_contact)
var vec:b2Vec2 = new b2Vec2(200,-400);

In this example, we test if the body in contact with the ball is jack. If true we set a new force that moves the ball up and to the right. In my simulation it is unlikely that the ball will collide with multiple special objects at the same time. So I'm happy to assume that there will only be one body in the contact list. If your ball will be in contact with multiple bodies you will want to check all bodies in the contact list.


Paul said...

Great post - thanks. I just played your Wheel game on Kongregate - very nice. It's great to see how you've put this technique to good use.

geekglue said...

Thanks. Glad you enjoyed the post and the game.

Anonymous said...

Hi Paul, I was just wondering if this was before vr2 of box2d - I tried it and I got an error...Is there another way to use the contact listener in vr2? Just trying to wrap my head around checking for collisions and it's driving me bonkers...


Dan said...

Hi, just wondering if this was pre vr2, I can't seem to get it to work but I'm guessing the class for ContactListNode just isn't how it's done anymore...Anyhow just wondering if you could elaborate on how to listen for collisions in vr2.0.


geekglue said...

This was well before vr2. I haven't had any time to look at the latest version. So I can't comment on the changes.