I am making a game but I can only get one bullet to fire, how can I get multiple bullets to fire when the space bar is pressed?
There is a main class. This contains the the size of the frame for the space game.
This is the shooter class. Here I draw the bullet and spaceship and set the left and right controls for the movement of the spaceship.
boolean right, left;
int bulletX;
int rectX = 320;
int rectY = 435;
int bulletY;
Rectangle bullet;
boolean space, fire;
boolean shot;
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);
if (shot) {
graphics.setColor(Color.RED);
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) {
if (bullet == null) {
fire = true;
if (fire) {
bulletX = rectX;
bulletY = rectY;
bullet = new Rectangle(bulletX + 25, bulletY, 3, 5);
shot = true;
}
}
}
}
public void shootBullet() {
if (shot) {
bullet.y--;
System.out.println("shot fired");
}