我试图做一个简单的javagame。其中一种方法创建一个具有随机x和y值的新矩形,然后将它们添加到列表中。 我希望我的程序检查是否要添加新的矩形,与当前的矩形相交,如果是,它应该得到新的x和y值。Java 2D游戏随机矩形
我做了应该工作的方法,但不知何故,不,我得到的错误:
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException.
该方法的代码是:提前
public void addObstacle() {
int x = (int)((Math.random() * 10)) * 40;
int y = (int)((Math.random() * 10)) * 20;
Rectangle newRec = new Rectangle(x, y, 20, 20);
for(Rectangle r : obstacles) {
if(newRec.intersects(r)) {
System.out.println("The new rectangle does intersect with " + r);
}
else {
obstacles.add(newRec);
}
}
repaint();
}
谢谢。
更新:加入修正:
Boolean doesCollide = false;
for(Rectangle r : obstacles){
if(newRec.intersects(r)){
System.out.println("The new rectangle does intersect with " + r);
doesCollide = true;
}
}
if(!doesCollide){
obstacles.add(newRec);
}
你能复制整个错误行吗? –