我目前正在开展一个学校项目,我正在尝试制作类似于galaga的游戏。我的问题是每当子弹击中敌人时,另一个敌人就会消失。我相信这是因为我正在使用for循环并且敌人正在按顺序删除。我遇到的另一个问题是子弹,我不知道为什么它减速并最终随着敌人数量的减少而消失。任何帮助表示赞赏。
ArrayList<enemy> e = new ArrayList<enemy>();
ArrayList<bullet> b = new ArrayList<bullet>();
boolean shoot = false;
void setup() {
fullScreen();
//enemy
for (int i = 0; i<5; i++) {
e.add(new enemy(50, 50));
}
//bullet
for (int i = 0; i<5; i++) {
b.add(new bullet(mouseX, mouseY));
}
}
void draw() {
background(255);
for (int p = 0; p<e.size(); p++) {
for (int i = 0; i<b.size(); i++) {
bullet a = b.get(i);
enemy o = e.get(p);
if (a.update()) {
b.remove(i);
}
if (o.col()) {
b.remove(i);
e.remove(i);
}
}
}
//enemy
for (int i = 0; i<e.size(); i++) {
enemy a = e.get(i);
a.display();
}
}
void mouseReleased() {
shoot = true;
b.add(new bullet(mouseX, mouseY));
}
class enemy {
int x, y, w, h;
int enemyX = int(random(width));
int enemyY = int(random(200));
public enemy(int tempenemyW, int tempenemyH) {
int tempenemyX = enemyX;
int tempenemyY = enemyY;
this.x = tempenemyX;
this.y = tempenemyY;
this.w = tempenemyW;
this.h = tempenemyH;
}
void display() {
fill(255, 0, 0);
rect(this.x, this.y, this.w, this.h);
}
boolean col() {
for (int i = 0; i<b.size(); i++) {
bullet a = b.get(i);
if (a.x+a.w>this.x && a.x<this.x+this.w && a.y+a.h+a.bulletSpeed>this.y && a.y+a.bulletSpeed<this.y+this.h) {
return true;
}
}
return false;
}
}
class bullet {
int x, y, w, h;
int bulletSpeed = 10;
public bullet(int tempx, int tempy) {
int tempw = 3;
int temph = 20;
this.x = tempx;
this.y = tempy;
this.w = tempw;
this.h = temph;
}
boolean update() {
this.y -= bulletSpeed;
fill(0, 255, 0);
rect(this.x, this.y, this.w, this.h, 100, 100, 100, 100);
if (x<0 || x>width || y<0 || y>height) {
return true;
} else {
return false;
}
}
}
答案 0 :(得分:0)
你移除生活在子弹索引处的敌人,而不是敌人索引处的敌人。要解决此问题,请尝试更改行
e.remove(i);
到
e.remove(p);
我还建议您提供更好的变量名称。这让你感到困惑的原因是因为&#34;我&#34;和&#34; p&#34;不是非常具有描述性或有帮助的。如果绘制函数的中间看起来像这样,那么发现错误会更容易:
for (int enemyIndex = 0; enemyIndex<e.size(); enemyIndex++) {
for (int bulletIndex = 0; bulletIndex<b.size(); bulletIndex++) {
bullet currentBullet = b.get(bulletIndex);
enemy currentEnemy = e.get(enemyIndex);
if (a.update()) {
b.remove(bulletIndex);
}
if (currentEnemy.col()) {
b.remove(bulletIndex);
e.remove(bulletIndex); // Clearly the wrong index!
}
}
}
然后你可以通过将你的名单更改为&#34;子弹&#34;和&#34;敌人&#34;而不只是&#34; b&#34;和&#34; e&#34; :P
答案 1 :(得分:0)
Teddy's answer是故事的一半。故事的另一半是你在循环时从列表中删除项目。
假设您有一个这样的循环:
for(int index = 0; index < list.size(); index++){
if(list.get(index).contains("remove me")){
list.remove(index);
}
}
让我们说你的清单看起来像这样:
0: "keep"
1: "remove me one"
2: "remove me two"
3: "keep"
记住这个列表的循环。当index
为0
时,它会看到"keep"
并且不执行任何操作。现在index
为1
,它会看到"remove me one"
,因此会删除索引1 处的项目,之后每个索引向下移动一个,使列表显示为:< / p>
0: "keep"
1: "remove me two"
2: "keep"
但是在循环结束时索引仍为1
,因此它会增加到2
,下一次迭代会看到"keep
“。
换句话说,我们跳过"remove me two"
,因为我们从来没有检查过它向下移动一个索引。
此问题的解决方案是使用Iterator
或在列表上向后循环。
无耻的自我推销:我写了一篇关于在Processing available here中使用ArrayLists的教程。请参阅有关从ArrayList中删除项目的部分。