Search code examples
javaandroidcollision-detectionandenginegame-physics

how to Detect Collision and Remove body and image after Collision


I am new on AndEngine and trying to detect collisions and destroy the body on collision. So far I have tried this.

 if (testingsprite.collidesWith(testingSprite1)) {
                Log.d("TAG", "Collisoion");
                mphysicworld.destroyBody(myBody);
                scene.detachChild(testingSprite1);
                myBody = PhysicsFactory.createCircleBody(this.mphysicworld,
                        testingSprite1, BodyType.DynamicBody, FIXTURE_DEF);
            }else{
                Log.d("TAG", "else Collisoion");
            }

`

But it does not work, and always goes into the else part. What should I do? I have tried with contactListener to but it become too messy and difficult to control. I am currently working with eclipse and physicsbox2dextention in andengine.


Solution

  • You should create a new "ContactListener" and bind it to your "PhysicsWorld" By "physicsWorldInstance.setContactListener(...)"

    and in the ContactListener override "beginContact". for example:

    public void beginContact(Contact contact)
        {
            final Fixture x1 = contact.getFixtureA();
            final Fixture x2 = contact.getFixtureB();
    
            if (x2.getBody().getUserData().equals("player")&&x1.getBody().getUserData().equals("monster"))
            {
              Log.d("TAG", "Collisoion");
            }
    
        }