我这里有两个数组列表,其中包含火箭和射弹:
public static ArrayList<Projectile> projectiles = new ArrayList<Projectile>();
private static ArrayList<Rocket> rockets = new ArrayList<Rocket>();
每隔一段时间,就会将射弹和火箭添加到适当的数组列表中:
rockets.add(new NormalRocket(x, -10, 70, 0, 2); // the constructor is (int x, int y, int speed, int dir, int health) but only x and y are relevant.
Rocket 和 Projectile 类都有以下方法:
public Rectangle bounds() {
return new Rectangle(x, y, width, height);
}
NormalRocket 和 MachineGunProjectile 等子类也有它:
public Rectangle bounds() {
return super.bounds();
}
现在,我有一个方法可以检查火箭和射弹之间的碰撞,如下所示:
private void collision(){
for(int i = 0; i < rockets.size(); i++){
for(int j = 0; j < projectiles.size(); j++){
if(rockets.get(i).bounds().intersects(projectiles.get(j).bounds())){
System.out.println("HIT!");
}
}
}
}
但是当它们相交时,似乎什么也没有发生。有人知道发生了什么或者这是否需要更多代码来调试?
最佳答案
我会给你一些提示来调试你的问题
尝试用文本绘制火箭和射弹的 x,y 位置。
也尝试绘制边界矩形,以便查看边界矩形是否真的正确绘制。
- 通过绘制两个可以相交的矩形来检查交集函数并检查输出值。
关于java - for 循环中的 .intersects() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19068296/