如何在Java Graphics中用布尔值实现Arkanoid砖块击中后消失
Hey there! Let's get those bricks to disappear when hit by the ball using a simple boolean flag—this is exactly the kind of straightforward solution you need for your demo. Here's how to integrate it into your existing Brickbase class:
Step 1: Add a Boolean Visibility Flag to Brickbase
First, we'll add a private boolean variable to track whether the brick should be visible (and interactable). This will act as our "on/off switch" for the brick.
Add this line to your class variables:
private boolean isVisible; // Tracks if the brick should be drawn and collide
Then initialize it to true in your constructor (since all bricks start visible):
public Brickbase(int x, int y, int xWidth, int yWidth, Color c) { myX = x; myY = y; myXWidth = xWidth; myYWidth = yWidth; myColor = c; isVisible = true; // Bricks start visible }
Step 2: Modify the draw Method to Respect the Flag
Update your draw method to only render the brick if isVisible is true. If it's false, nothing gets drawn—making the brick appear to disappear:
public void draw(Graphics myBuffer) { if (isVisible) { // Only draw if the brick is visible myBuffer.setColor(getColor()); myBuffer.fillRect(getX(), getY(), getXWidth(), getYWidth()); } }
Step 3: Update Collision Detection to Toggle the Flag
Your current inBrickbase method checks for collisions, but we need to tweak it to:
- Only check collisions if the brick is visible (no need to interact with already destroyed bricks)
- Set
isVisibletofalsewhen a collision is detected
Here's the updated method:
public boolean inBrickbase(arkBall ark) { if (!isVisible) { // Skip collision check if brick is already gone return false; } for(int x = getX(); x <= getX() + getXWidth(); x++) for(int y = getY(); y <= getY() + getYWidth(); y++) if(distance(x, y, ark.getX(), ark.getY()) <= ark.getRadius() ) { isVisible = false; // Mark brick as destroyed return true; // Collision detected } return false; }
How This Works
- The
isVisibleboolean acts as a state tracker:truemeans the brick is active (drawn and can collide),falsemeans it's destroyed (invisible and ignores collisions) - When the ball hits the brick, we flip the flag to
false—so the next time the game draws, the brick doesn't show up, and future collision checks skip it entirely - This keeps your code simple and aligned with the boolean-based approach you wanted!
Just make sure in your main game loop, you're still calling draw() on all bricks—this method will now handle hiding the destroyed ones automatically.
内容的提问来源于stack exchange,提问作者ShiMin Chen

