Java游戏开发:如何实现按键时重复发射多发子弹?
解决太空游戏多发子弹发射问题
你的代码只能发射一颗子弹,核心原因是用了单个Rectangle bullet变量存储子弹,每次新发射的子弹会覆盖旧的,且仅有一个shot状态控制显示。要实现多发子弹,只需将单个子弹变量改为集合存储所有子弹,再对集合做增删改查操作即可,具体修改步骤如下:
1. 替换单个子弹变量为集合
删除原有的单个子弹相关变量,改用集合存储所有子弹:
// 移除以下变量: // Rectangle bullet; // boolean shot; // boolean fire; // 替换为集合存储所有子弹 List<Rectangle> bullets = new ArrayList<>();
2. 修改空格键发射逻辑
在keyPressed方法中,按空格键时直接创建新子弹并加入集合,无需再判断单个子弹是否为空:
if (e.getKeyCode() == KeyEvent.VK_SPACE) { // 计算子弹初始位置(飞船中心) int bulletX = rectX + 25; int bulletY = rectY; bullets.add(new Rectangle(bulletX, bulletY, 3, 5)); }
3. 修改绘制逻辑,遍历绘制所有子弹
在paintComponent中,遍历集合绘制每一颗子弹:
// 移除原有单个子弹绘制代码: // if (shot) { // graphics.setColor(Color.RED); // graphics.fillRect(bullet.x, bullet.y, bullet.width, bullet.height); // } // 替换为遍历集合绘制所有子弹 graphics.setColor(Color.RED); for (Rectangle bullet : bullets) { graphics.fillRect(bullet.x, bullet.y, bullet.width, bullet.height); }
4. 修改子弹移动逻辑,清理超出屏幕的子弹
在shootBullet方法中,遍历所有子弹实现移动,同时移除飞出屏幕的子弹(避免内存浪费):
public void shootBullet() { // 用迭代器遍历,避免遍历中修改集合出现异常 Iterator<Rectangle> iterator = bullets.iterator(); while (iterator.hasNext()) { Rectangle bullet = iterator.next(); bullet.y--; // 子弹飞出屏幕顶部时移除 if (bullet.y + bullet.height < 0) { iterator.remove(); } } }
完整修改后的核心代码片段
boolean right, left; int rectX = 320; int rectY = 435; // 集合存储所有子弹 List<Rectangle> bullets = new ArrayList<>(); public ShooterGame() { addKeyListener(this); this.setFocusTraversalKeysEnabled(false); this.setFocusable(true); } public void paintComponent(Graphics graphics) { graphics.setColor(Color.BLUE); graphics.drawRect(0, 0, 700, 500); graphics.fillRect(0, 0, 700, 500); graphics.setColor(Color.YELLOW); graphics.drawRect(rectX, rectY, 50, 30); graphics.fillRect(rectX, rectY, 50, 30); // 绘制所有子弹 graphics.setColor(Color.RED); for (Rectangle bullet : bullets) { graphics.fillRect(bullet.x, bullet.y, bullet.width, bullet.height); } repaint(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT) { moveToRight(); } if (e.getKeyCode() == KeyEvent.VK_LEFT) { moveToLeft(); } if (e.getKeyCode() == KeyEvent.VK_SPACE) { // 每次按空格新增一颗子弹 int bulletX = rectX + 25; int bulletY = rectY; bullets.add(new Rectangle(bulletX, bulletY, 3, 5)); } } public void shootBullet() { Iterator<Rectangle> iterator = bullets.iterator(); while (iterator.hasNext()) { Rectangle bullet = iterator.next(); bullet.y--; // 清理飞出屏幕的子弹 if (bullet.y + bullet.height < 0) { iterator.remove(); } } }
修改后,每次按空格键都会发射新子弹,所有子弹会同步向上移动,飞出屏幕后自动被清理,即可实现多发子弹的效果。
内容的提问来源于stack exchange,提问作者Ronan
相关产品推荐
相关产品推荐

