1

im developing a game using andangine and the tmx and body2d extensions. i create Objects(sprites) like coins an specific positions while creating my map. i use a contactlistener to check if the player collides with a coin.

how can i delete this sprite? and how can i organize my sprites best? thanks =)

blub
  • 21
  • 2

2 Answers2

1

I assume you create a PhysicsConnector to connect between your sprites and bodies. Create a list of these physics connectors, and when you decide you should remove a body (And its sprite), do the following:

Body bodyToRemove = //Get it from your contact listener
for(PhysicsConnector connector : mPhysicsConnectors) //mPhysicsConnectors is the list of your coins physics connectors.
    if(connector.getBody() == bodyToRemove)
        removeSpriteAndBody(connector); //This method should also delete the physics connector itself from the connectors list.

About sprites organization: Coins are re-useable sprite, you shouldn't recreate them every time. You can use an object pool, here's a question about this topic.

Community
  • 1
  • 1
Jong
  • 9,045
  • 3
  • 34
  • 66
  • ok. i did a method like removeSpriteAndBody but my app crashes when this method gets called. -25 23:50:51.869: E/AndroidRuntime(15700): FATAL EXCEPTION: UpdateThread 11-25 23:50:51.869: E/AndroidRuntime(15700): java.util.ConcurrentModificationException 11-25 23:50:51.869: E/AndroidRuntime(15700): at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:576) – blub Nov 25 '12 at 22:54
  • 1
    try this: Iterator iterator = mPhysicsConnectors.iterator(); while(iterator.hasNext()) { connector = iterator.next(); if (connector.getBody() == needToRemove) { iterator.remove(); removeSpriteAndBody(connector); } } – Aleksandrs Nov 26 '12 at 06:06
  • I encountered this problem too when I implemented something similar in my game. Use what Racoon said, it should work. – Jong Nov 26 '12 at 08:14
  • still the same error, i guess its my removeSpriteAndBody-method. protected void removeSpriteAndBody(PhysicsConnector connector) { physicsConnectors.remove(connector); scene.detachChild(connector.getShape()); – blub Nov 26 '12 at 10:30
  • did you remove iterator before call removeSpriteAndBody? – Aleksandrs Nov 26 '12 at 10:56
0

I advice you to set user data of a body. And in your collision handler you would be able to work with it. Small example:

body.setUserData(...);

..

    public void postSolve(Contact contact, ContactImpulse impulse) {

            ... bodyAType = (...) bodyA.getUserData();
            ... bodyBType = (...) bodyB.getUserData();
            if (bodyAType != null && bodyBType != null) {
               if (bodyAType.getUserData.equals(...)) {
                   //.......do what you need
               }
            }
    }
SVS
  • 200
  • 9