From: Himi "Android game programming from scratch" www.himigame.com
A collision listener Interface "Contactlistener" is provided in box2d, which uses an interface that requires rewriting its four abstract functions.
@Override public
void Add (ContactPoint arg0) {
//TODO auto-generated Method stub
//Collision, response to this function
when there is a new contact point }
@Override public
void persist (ContactPoint arg0) {
//TODO auto-generated Method stub
// Respond to this function when an existing contact point persists
} @Override public
void Remove (ContactPoint arg0) {
//TODO auto-generated method Stub
//Response to this function when the presence of a touch point is deleted
}
@Override public
void result (Contactresult arg0) {
//TODO auto-generated method Stub
//per time step monitoring, if there is still a contact presence is responded to
}
Through the instance of the parameter ContactPoint class, we can get the two body instances that collide with each other, get the body instance method as follows:
Body body1 = Arg0.shape1.getBody ();
Body body2 = Arg0.shape2.getBody ();
The application is as follows:
if (arg0.shape1.getBody () = = Bodyball && arg0.shape2.getBody () = = lostBody1) {
gameislost = true;
} else if (arg0.shape1.getBody () = = Bodyball && arg0.shape2.getBody () = = LostBody2) {
gameislost = true;
} else if (arg0.shape1.getBody () = = Bodyball && arg0.shape2.getBody () = = Winbody) {
Gameiswin = true;
}
Finally, make sure to bind the listener to the physical world instance:
World.setcontactlistener (Contactlistener listener);