Java for循环数组列表无法正常工作

时间:2022-01-14 18:14:46

I'm making a tower defense game in Java but I have a problem with for loops and ArrayLists. I have a similar piece of code in my Tower.java class (used for buildings, stuff you use for shooting/defense):
for (Enemy e : enemies) { shoot(); }

我正在使用Java制作塔防游戏,但我遇到了for循环和ArrayLists的问题。我的Tower.java类中有一段类似的代码(用于建筑物,用于拍摄/防御的东西):for(Enemy e:enemies){shoot(); }

Whenever my things shoot, they pick the last instance of Enemy.class and create a new instance of my Bullet.java class which then move towards the enemy (last one in the arraylist). What I want is the tower/building to pick the first or nearest one and shoot towards it. Any ideas on how to do this?

每当我的事情发生时,他们选择Enemy.class的最后一个实例并创建一个我的Bullet.java类的新实例,然后向敌人移动(最后一个在arraylist中)。我想要的是塔/建筑物选择第一个或最近的一个并向它射击。关于如何做到这一点的任何想法?

EDIT:
Here's my Tower.java class: http://pastebin.com/uEiQ4F20

编辑:这是我的Tower.java类:http://pastebin.com/uEiQ4F20

This problem is pretty much the same I have had in other projects as well. Basically, going through every instance of a class in an ArrayList seems to be not working very well, because whatever I do inside the loop, it only affects the last instance of the class in the ArrayList.

这个问题与我在其他项目中的问题非常相似。基本上,遍历ArrayList中的每个类的实例似乎都不能很好地工作,因为无论我在循环中做什么,它只会影响ArrayList中类的最后一个实例。

EDIT:
Apparently, someone removed the Enemy.java paste from pastebin, so here it is again: http://pastebin.com/jMGNVBLQ

编辑:显然,有人从pastebin中删除了Enemy.java粘贴,所以这里又是:http://pastebin.com/jMGNVBLQ

1 个解决方案

#1


0  

I kind of solved the problem by adding the following line of code:
if (!enemy.removed && enemy == level.enemies.get(level.enemiesKilled))

我通过添加以下代码行解决了这个问题:if(!enemy.removed && enemy == level.enemies.get(level.enemiesKilled))

#1


0  

I kind of solved the problem by adding the following line of code:
if (!enemy.removed && enemy == level.enemies.get(level.enemiesKilled))

我通过添加以下代码行解决了这个问题:if(!enemy.removed && enemy == level.enemies.get(level.enemiesKilled))