我在java中制作一个简单的2D游戏,我正在努力争取工作。我打算做口袋妖怪式的战斗,所以我正在做的是当我按空格键时,它检查我是否与敌人发生碰撞,在arrayList中找到敌人,然后使用该敌人执行战斗方法。这在大多数情况下都有效,但有时它似乎无法在ArrayList中找到敌人。我检查这个的代码是:
if (space) {
for (Rectangle collideable : Enemy.ens) {
if (intersects(playerR, collideable)) {
System.out.println("Colliding with Enemy!");
x = locx;
y = locy;
playerR.setLocation(x, y);
for (int i = 0; i < Game.enemies.size(); i++) {
if (Enemy.ens.get(i).equals(collideable)) {
System.out.println("Can't find enemy to fight");
System.out.println(Game.enemies.get(i).getName());
fightQuestion(Game.enemies.get(i), i);
break;
}
}
break;
}
}
}
当我渲染每个敌人时,会创建 Enemy.ens
。当我读入所有敌人的统计数据时,会创建Game.enemies
,然后我将每个敌人添加到该ArrayList。对于我试图战斗的每一个敌人来说,它已经到了打印出它碰撞的地步,但并不总是对战斗部分。关于为什么会发生这种情况的任何想法都会很棒!
EDIT Game.Enemies填充时的代码:
public static void loadEnemies() {
im = getImageManager();
Scanner qwe;
try {
qwe = new Scanner(new File("enemyStats.txt"));
while (qwe.hasNextLine()) {
String name = qwe.nextLine();
String origin = qwe.nextLine();
String weapon = qwe.nextLine();
String gear = qwe.nextLine();
String spec = qwe.nextLine();
int hp = qwe.nextInt();
int att = qwe.nextInt();
int def = qwe.nextInt();
int randX = (int) (Math.random()*(18*SCALE*TILESIZE)); //Give random x coordinate
int randY = (int) (Math.random()*(18*SCALE*TILESIZE)); //Give random y coordinate
if(qwe.hasNextLine()){
qwe.nextLine();
}
enemies.add(new Enemy(randX,randY,im,name,origin,weapon,gear,spec,hp,att,def)); //adds enemy into arrayList
int randI = (int) (Math.random()*enemies.size());
for(int i = 0; i < 4;i++){ //adds enemy to arrayList to be rendered
enemiestoRend.add(enemies.get(randI) );
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
为什么要执行声明:
System.out.println("Can't find enemy to fight");
对于第二个循环中的每次迭代,无论先检查条件如何?为什么第二次循环检查:
i < Game.enemies.size();
而不是:
i < Enemy.ens.size();