2

I have an android game which involves a ship shooting enemies. I am trying to make it so that if the enemies are within a certain distance of the ammos, then the enemys remove themselves from the screen. I have attempted to do it and the code compiles, but i am unsure why the enemys arent being removed from the screen once been hit. Can anyone see anything wrong with the code below? Thankyou

for (TopEnemy i : newTopEnemy)
{
    for (int q = 0; q < ammo.length; q++)
    {
       float xsubs = i.enemyX - ammo[q].positionX;
       float ysubs = i.enemyY - ammo[q].positionY;
       float squared = (xsubs * xsubs) + (ysubs * ysubs);
       float distance = (float)Math.sqrt(squared);
       if (distance < 10.0)
       {
          newTopEnemy.remove(q);
       }
    }
 }  

4 Answers 4

5

Shouldn't it be newTopEnemy.remove(i); ? q looks like an index on ammo.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to use Iteratore.remove.

for (Iterator<TopEnemy> itr = intList2.iterator(); iterator.hasNext();) {
    TopEnemy enemy = itr.next();
    //code here 
    if (distance < 10.0) {
            itr.remove();
    }
}

2 Comments

So it should look something like this? 'for (Iterator<TopEnemy> itr = intList2.iterator(); iterator.hasNext();) { TopEnemy enemy = itr.next(); for (TopEnemy i : newTopEnemy) { for (int q = 0; q < ammo.length; q++) { float xsubs = i.enemyX - ammo[q].positionX; float ysubs = i.enemyY - ammo[q].positionY; float squared = (xsubs * xsubs) + (ysubs * ysubs); float distance = (float) Math.sqrt(squared); if (distance < 10.0) { itr.remove(); } } } }'
@user3426043 the iterator should be replaced by your for-each loop.
1

You cannot remove from a list while using the foreach loop. You have to use an iterator to loop through the list and then remove using the remove method.

Comments

0

I would add to Vlad answer that is not always a good ideea to remove an item while looping over a list like that. I would do it like this :

for (int i = newTopEnemy.size()-1;i>=0;i--) {
    TopEnemy enemy = newTopEnemy.get(i);
    for (int q = 0; q < ammo.length; q++) {
        float xsubs = enemy.enemyX - ammo[q].positionX;
        float ysubs = enemy.enemyY - ammo[q].positionY;
        float squared = (xsubs * xsubs) + (ysubs * ysubs);
        float distance = (float)Math.sqrt(squared);
        if (distance < 10.0) {
            newTopEnemy.remove(i);
            break;
        }
    }
} 

1 Comment

this way, if you are lucky you'll get an ArrayIndexOutBoundException

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.