I’m looking to make a simple space invaders type shooter for android and i’m having trouble making the bullets kill the enemies. I’m not so concerned with the collision itself, but the arrayList functions are baffling me. I have an arrayList of bullets and another of bad guys each with their respective x and y placement. I’m trying to make it so that if they collide, the corresponding bad guy disappears. Unfortunately when I try to do this, i’m getting force closes so its really hard to debug. Here’s the relevant code:
Within Bullet.class:
public List<Placement> bulletsArray = new ArrayList<Placement>();
public List<Placement> temp = new ArrayList<Placement>();
public List<Integer> tempKill = new ArrayList<Integer>();
public List<Integer> kill(List<Placement> badguys){
for (int i = bulletsArray.size() ; i >= 0 ; i--){
Placement bulletsBang = bulletsArray.get(i);
for (int j = badguys.size(); j >=0 ; j--){
Placement badGuys = badguys.get(j);
if (bulletsBang.x == bulletsBang.y ){
if (badGuys.x == bulletsBang.x && badGuys.y == bulletsBang.y){
tempKill.add(j);
}
}
}
// tempKill.add(0); //Just using this to get something to work.
// temp.add(bullets.get(i)); // should destroy the bullet when it hits.
}
return tempKill;
}
Within World.class:
public void update(float deltaTime) {
if (gameOver)
return;
tickTime += deltaTime;
while (tickTime > tick) {
tickTime -= tick;
bullet.advance();
bullet.deleteExtra();
slowDown++;
if (slowDown == 2){
badGuy.advance();
slowDown = 0;
}
if (bullet.bulletsArray.size() > 0){
badGuy.kill(bullet.kill(badGuy.badguys));
}
}
}
Within BadGuy.class;
public List<Placement> badguys= new ArrayList<Placement>();
public BadGuy (){
for (int i = 0 ; i < 8; i++){
if (i% 2 == 0 ){
badguys.add(new Placement(1 + i, 0));//creates 3 rows of bad guys.
badguys.add(new Placement(1 + i, 1));
badguys.add(new Placement(1 + i, 2));
}
}
}
public void kill(List<Integer> die){
for (int i = die.size() ; i >= 0 ; i --){
badguys.remove(die.get(i));
}
}
I can get the badguys to be removed when I use an Integer. But I want to return the arrayList to remove the badguys I get the force close.
Your reverse loop must start at size()-1. size() is 1 past the last element and will throw an exception.
EDIT
Also, I would suggest that your routine
kill()return aList<Placement>, not aList<Integer>of indices. That is simpler conceptually (at least to me, YMMV) andBadGuy.kill()simply does aremoveAll()