飛機遊戲中子彈數量大、頻繁生成銷毀,若每顆子彈對應一個 Sprite 會嚴重消耗記憶體。解決方案:共享單一 Sprite,以二維陣列管理子彈狀態。
public class Bullets extends GameObject {
private int[][] bullets; // [index][0:type, 1:x, 2:y, 3:vx, 4:vy, 5:alive]
private int bulletsTotal;
private Random rnd;
public static final int TYPE_LEFT=0, TYPE_RIGHT=1, TYPE_TOP=2, TYPE_BOTTOM=3;
private int screenW, screenH;
public Bullets(Image img, int pw, int ph, int total, int w, int h) {
super(img, pw, ph);
bulletsTotal = total;
bullets = new int[total][6];
rnd = new Random();
screenW = w; screenH = h;
}
public void initBullets() { for(int i=0;i screenW+5) bullets[i][3] *= -1;
if (bullets[i][2] < -5 || bullets[i][2] > screenH+5) bullets[i][4] *= -1;
}
public void paint(Graphics g) {
for (int i=0; i
setPosition() 移動共享 Sprite,極大降低記憶體壓力。Bullets(Image, pw, ph, total, w, h) 建構子initBullets() 初始化全群paint(Graphics) 繪製全群refreshBullets(Sprite, boolean) 邏輯更新與碰撞檢測killBullets(Sprite, int) 範圍清除(導彈道具)