0

I'm working on this game where you keep a tower from being hit 3 times by incoming missiles.

The variable g is the counter. Once it reaches 3, I want the tower to disappear. Instead, it gets hit once and then disappears. I'm guessing this is because the g=g+! is probably looping many times instead of just once at a time.

What is a better way of going about this? I will appreciate any help.

public void onUpdate(float pSecondsElapsed) {
if(i.ttower.collidesWith(u.ennemy))
    {

    final float x = u.ennemy.getX();
    final float y = u.ennemy.getY();

        i.ShakeTower();
        u.ennemy.detachSelf();
        g=g+1;
        if(g==3)
            i.ttower.detachSelf();

    }
       }

1 Answers1

0

You are correct, g=g+1 is getting called many times in rapid succession because your contact is occurring over several iterations of the update handler. You can sub-class Sprite and create a member variable (with a getter and setter) that serves as a flag for whether or not the collision has occurred and initialize it to false. Then make the following modification:

public void onUpdate(float pSecondsElapsed) {
if(i.ttower.collidesWith(u.ennemy))
    {

        if(!u.ennemy.getHasCollided())
        {

            final float x = u.ennemy.getX();
            final float y = u.ennemy.getY();

            i.ShakeTower();
            u.ennemy.detachSelf();
            g=g+1;
            if(g==3)
            i.ttower.detachSelf();

            u.ennemy.setHasCollided(true);
         }

    }
}
jteezy14
  • 436
  • 4
  • 11