[英]Java 2d game finding correct enemy for fighting
我正在用Java做一个简单的2D游戏,我正在努力争取上班。 我将进行口袋妖怪式的战斗,所以我要做的是当我按下空格键时,它会检查我是否正在与敌人碰撞,在arrayList中找到该敌人,然后使用该敌人执行Fight方法。 在大多数情况下,这是可行的,但有时似乎无法在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中。 对于我尝试与之战斗的每个敌人,它都达到了打印冲突的地步,但并非总是如此。 关于为什么发生这种情况的任何想法都太棒了!
填满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();
}
}
为什么执行该语句:
System.out.println("Can't find enemy to fight");
对于第二个循环中的每次迭代,无论先检查条件如何? 以及为什么第二个循环检查:
i < Game.enemies.size();
代替:
i < Enemy.ens.size();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.