I’m still new to java and android programming and I am having so much trouble Removing an object when collision happens. I looked around the web and found that I should never handle removing BOX2D bodies during collision detection (a contact listener) and I should add my objects to an arraylist and set a variable in the User Data section of the body to delete or not and handle the removing action in an update handler. So I did this: First I define two ArrayLists one for the faces and one for the bodies:
ArrayList<Sprite> myFaces = new ArrayList<Sprite>();
ArrayList<Body> myBodies = new ArrayList<Body>();
Then when I create a face and connect that face to its body I add them to their ArrayLists like this:
face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mBoxFaceTextureRegion);
Body BoxBody = PhysicsFactory.createBoxBody(mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, BoxBody, true, true));
myFaces.add(face);
myBodies.add(BoxBody);
now I add a contact listener and an update handler in the onloadscene like this:
this.mPhysicsWorld.setContactListener(new ContactListener() {
private AnimatedSprite face2;
@Override
public void beginContact(final Contact pContact) {
}
@Override
public void endContact(final Contact pContact) {
}
@Override
public void preSolve(Contact contact,Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact,ContactImpulse impulse) {
}
});
scene.registerUpdateHandler(new IUpdateHandler() {
@Override
public void reset() { }
@Override
public void onUpdate(final float pSecondsElapsed) {
}
});
My plan is to detect which two bodies collided in the contact listener by checking a variable from the user data section of the body, get their numbers in the array list and finally use the update handler to remove these bodies.
The questions are: Am I using the arraylist correctly? How to add a variable to the User Data (the code please). I tried removing a body in this update handler but it still throws me NullPointerException , so what is the right way to add an update handler and where should I add it. Any other advices to do this would be great. Thanks in advance.