Hello,
I’m trying to make a Space invader like game for a school project, but I have a problem with collisions: I have an arry wich contain shot’s coordonates and an other which contain ennemis oordonates. Ennemies spawns regulary and shots spawn faster than them. if you just clic on each ennemi It work, but if you play with auto fire and miss some aliens, the game crash. I don’t know how to resolve the “array out of bound exetion” error. It seem like when autofire is activate, one array contain more cases than the other, but after weeks of reseach I don’t even know how to make it function.
I use two nested/embedded ( I’m not english, I don’t know the right word) “for” which run each aliens for each shots.
It sound you have identified problem. Array out of range exception means that program has tried to use array with an index value bigger than array size. It’s a bit difficult to tell anything else without the code.
Usually when you go through arrays with for loops structure is like this
for( int i = 0; i < arrayX.length; i++) {
arrayX[i] = random();
}
Then you cannot index out of arrays size. Indexing of arrays start from 0 and last index is length-1
FloatList listeXenemi = new FloatList(); // listeX est la liste des abscisses des enemis. Au départ, cette liste est vide.
FloatList listeYenemi = new FloatList();
FloatList listeXshots = new FloatList(); // listeX est la liste des abscisses des balles. Au départ, cette liste est vide.
FloatList listeYshots = new FloatList();
void collision(){
for (int i =0 ; i<listeXenemi.size() ; i++) {
for (int j =0 ; j<listeXshots.size() ; j++) {
if ((dist(listeXenemi.get(i),listeYenemi.get(i),listeXshots.get(j),listeYshots.get(j)) < 50))
{
listeXenemi.remove(i);
listeYenemi.remove(i);
listeXshots.remove(j);
listeYshots.remove(j);
}
}
}
}
I have posted all few min ago but it was impossible to read, I don’t know if you can see deleted coments so here is the most important part
void collision() {
for (int i = listeXenemi.size() - 1; i >= 0; i--) {
for (int j = listeXshots.size() - 1; j >= 0; j--) {
if ((dist(listeXenemi.get(i), listeYenemi.get(i), listeXshots.get(j), listeYshots.get(j)) < 50)) {
listeXenemi.remove(i);
listeYenemi.remove(i);
listeXshots.remove(j);
listeYshots.remove(j);
break; // This is needed so you don't keep checking for an enemy that doesn't even exist anymore
}
}
}
}
You have to do this whenever you’re removing from a list in a loop.