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);
this.ball.SetLinearVelocity(vec);
}
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.
5 comments:
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.
Thanks. Glad you enjoyed the post and the game.
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...
Thanks
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.
Thanks,
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.
Post a Comment