Game Development Reference
In-Depth Information
2.
You already know how a userData property works, so the core of the
function and of the entire chapter lies in the following line:
world.SetContactListener(new customContact());
Box2D allows us to create a custom contact listener that supports all the
events we need to manage collisions, such as when a collision starts and
ends, mostly in the same way you are used to dealing with events such as
mouse or keyboard events in your AS3 projects.
Box2D built-in collision listener
Without entering too much into the Box2D source code, you should know that it
not only solves collisions on its own, but also provides four interesting listeners that
allow you to interact with collision, retrieving information, or even modifying some
parameters. Everything will be managed within a new class I called customContact ,
thanks to the SetContactListener method, which allows us to create custom
contact callbacks.
Having said this, create a new file called customContact.as and write the following
lines of code:
package {
import Box2D.Dynamics.*;
import Box2D.Collision.*;
import Box2D.Dynamics.Contacts.*;
public class customContact extends b2ContactListener {
override public function BeginContact(contact:b2Contact):void{
trace("a collision started");
var fixtureA:b2Fixture=contact.GetFixtureA();
var fixtureB:b2Fixture=contact.GetFixtureB();
var bodyA:b2Body=fixtureA.GetBody();
var bodyB:b2Body=fixtureB.GetBody();
trace("first body: "+bodyA.GetUserData());
trace("second body: "+bodyB.GetUserData());
trace("---------------------------");
}
override public function EndContact(contact:b2Contact):void{
trace("a collision ended");
var fixtureA:b2Fixture=contact.GetFixtureA();
var fixtureB:b2Fixture=contact.GetFixtureB();
var bodyA:b2Body=fixtureA.GetBody();
var bodyB:b2Body=fixtureB.GetBody();
 
Search WWH ::




Custom Search