【发布时间】:2011-09-08 11:08:25
【问题描述】:
我正在制作一款垂直射击游戏,但在碰撞检测方面遇到了问题。通过 Rectangle 方法“intersect”检测碰撞,但为了跟踪可能发生碰撞的所有内容,我需要 Arraylists 来跟踪所有子弹和敌舰。 Enemy 和 Player 类都产生 Bullets(它们也有自己的类),所以我想在我的 GameView 类中有 2 个不同的 Arraylist(它控制游戏图形并希望在这里完成后发生碰撞)。
在生成时允许将子弹添加到其各自的 ArrayList 的最有效方法是什么?
子弹类:
public class Bullet extends Location{
private Fights bulletOwner;
private int damage;
private int velocity;
public Bullet(Fights owner, int dmg, Rectangle loca)
{
super(loca);
bulletOwner = owner;
damage = dmg;
}
public Fights getOwner(){return bulletOwner;}
public int getDamage(){return damage;}
public int getVelocity(){return velocity;}
}
位置类
import java.awt.Rectangle;
public class Location {
protected Rectangle loc;
public Location (Rectangle location)
{
loc = location;
}
public Rectangle getLocation()
{
return loc;
}
public void updateLocation(Rectangle location)
{
loc = location;
}
}
【问题讨论】:
-
使用多线程时要小心。数组列表的并行修改可能会导致奇怪的异常(对于 i : list.size())-> 越界,因为其他一些线程刚刚删除了一个元素并且大小已经改变。 Collections.synchronizedList 或者 CopyOnWriteArrayList 可能是更好的选择。