检测数组中对象之间的冲突

时间:2013-12-11 18:34:46

标签: arraylist collision-detection processing detection collision

所以我需要检测存储在两个不同数组或arrayLists中的多个对象的冲突。我已经确认碰撞检测方法本身运行正常。问题是碰撞的物体应该消失并从阵列中移除,我不知道该怎么做。

 public class GamePanel extends PApplet{
private boolean myRunningStatus;
private final int HEIGHT = 700;
private final int WIDTH = 1200;
private final int SHOT_SPEED = -20;
private int numStars = 0, numEnemies = 0;
private Hero hero;
private Enemy[] enemies; 
private List <Star> stars;

public GamePanel(){
    myRunningStatus = true;
    createEnemies();
    createStars();
    createHero();
    updateEnemies();
}

public void createEnemies(){
    enemies = new Enemy[10];
    for (int i=0; i<enemies.length; i++){
        enemies[i] = new Enemy(random(1, WIDTH), random(1, HEIGHT), 5, 20);
    }
}

public void createHero(){
    hero = new Hero(mouseX, mouseY);
}

public void createStars(){
    stars = new ArrayList <Star>();
}

public Star generateStar(){
    Star star = new Star(hero.getHeroX(), hero.getHeroY());
    return star;
}


public void setup(){
  background(255);
  size(WIDTH, HEIGHT);
  hero.render(this);
}

public void draw(){
if(myRunningStatus){
  background(255);
  hero.render(this);
 for(int i=0; i<enemies.length; i++){
  enemies[i].render(this);
  enemies[i].move();
 }
     for(int i=0; i<stars.size(); i++){
         if(stars.get(i) != null){
             stars.get(i).render(this);
             stars.get(i).move(SHOT_SPEED);
             if(stars.get(i).getYPos() < 0){
                 stars.remove(i);
         }
     }
 }
}
}

//this is the method I'm using to find the collisions between the objects and remove them
public void updateEnemies(){
    for(int i=0; i<enemies.length; i++){
    for(int j=0; j<stars.size(); j++){
        if(enemies[i].starHit(stars.get(j))){
            stars.set(j, null);
            enemies[i] = null;
        }
        }
    }
}


public void mouseMoved(){
if(myRunningStatus){
  hero.setHeroX(mouseX);
  hero.setHeroY(mouseY);
    }
}

public void mouseClicked(){
     for (int i=0; i<10;){
             stars.add(i, generateStar());
             break;
     }
}

1 个答案:

答案 0 :(得分:1)

不是将事物设置为等于null,而是最好从列表中删除它们。我会为enemiesstars使用ArrayList,然后在碰撞检测期间调用list.remove(i)。不要忘记这会改变列表的大小,因此每次删除要补偿的元素时都必须执行i--

另外,这让我很困惑。您将enemies的元素设置为null:

    if(enemies[i].starHit(stars.get(j))){
        stars.set(j, null);
        enemies[i] = null;
    }

但是不要在这里检查,所以你不应该得到NPE吗?

 for(int i=0; i<enemies.length; i++){
  enemies[i].render(this);
  enemies[i].move();
 }