Question

so I have this code, I'm trying to learn Java and this is basically my first game, it's similar to SubmarineKiller where you are a boat, launching bombs at the submarine. My class below is the bomb. When I press the Down arrow, the bomb launches but I can't launch another one until it hits the submarine or it goes out of screen. My question is: How can I fire the next bomb as soon as the first one left the boat? Basically launch a bomb anytime I press my down key.

public void keyPressed(KeyEvent evt) {
       int code = evt.getKeyCode();
       if (code == KeyEvent.VK_DOWN) {
        if (bomb.isFalling == false)
            bomb.isFalling = true;
       }
}

-

    private class Bomb {
        int centerX, centerY;
        boolean isFalling;

        Bomb() {
            isFalling = false;
        }

        void updateForNewFrame() {
            if (isFalling) {
                if (centerY > height) {
                    isFalling = false;
                }
                else 
                    if (Math.abs(centerX - sub.centerX) <= 36 && Math.abs(centerY - sub.centerY) <= 21) {
                        sub.isExploding = true;
                        sub.explosionFrameNumber = 1;
                        isFalling = false; // Bomba reapare in barca
                    }
                    else {
                        centerY += 10;
                    }
            }   
        }

        void draw(Graphics g) {
            if ( !isFalling ) {
                centerX = boat.centerX;
                centerY = boat.centerY + 23;
            }
             g.setColor(Color.RED);
             g.fillOval(centerX - 8, centerY - 8, 16, 16); 
        }
}
Was it helpful?

Solution

You need to rewrite your code in terms of a list of bombs rather than a single bomb. Then, your key pressed event needs to change to add a new bomb to the list rather than just setting the properties of the single bomb. Your processing code will then also need to change - you'll need to loop over the list and process each bomb in turn.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top