[英]Removing from an arraylist android
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. 我试图让它成为如果敌人在ammos的一定距离内,那么敌人将自己从屏幕上移开。 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);
}
}
}
Shouldn't it be newTopEnemy.remove(i);
不应该是newTopEnemy.remove(i);
? ? q
looks like an index on ammo
. q
看起来像ammo
的索引。
You need to use Iteratore.remove
. 你需要使用Iteratore.remove
。
for (Iterator<TopEnemy> itr = intList2.iterator(); iterator.hasNext();) {
TopEnemy enemy = itr.next();
//code here
if (distance < 10.0) {
itr.remove();
}
}
You cannot remove from a list while using the foreach loop. 使用foreach循环时无法从列表中删除。 You have to use an iterator to loop through the list and then remove using the remove method. 您必须使用迭代器遍历列表,然后使用remove方法删除。
I would add to Vlad answer that is not always a good ideea to remove an item while looping over a list like that. 我会添加到Vlad的回答,并不总是一个很好的想法,在循环这样的列表时删除一个项目。 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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.