Java 中的冲突检测



我正在制作一个突破游戏。我有两个类:一个显示砖块图像数组的砖块类和一个在窗口周围移动球图像的球类。我试图弄清楚当球碰到其中一块砖时如何让砖消失。任何帮助将不胜感激。

砖类:

public class Brick {
    private URL url;
    private Image brick;
    Image [][] bricks = new Image[50][3];
    public Brick (Breakout bR){
        url = bR.getDocumentBase();
        brick = bR.getImage(bR.getDocumentBase(),"brick.png"); 
        for(int i =0; i < bricks.length; i++)
            for(int j = 0; j < bricks[0].length; j++)
                bricks[i][j] = brick;
    }
    public void update(Breakout bR){}
    public void paint(Graphics g, Breakout bR){
        brick = bR.getImage(bR.getDocumentBase(),"brick.png"); 
        int imageWidth = imageWidth = bricks[0][0].getWidth(bR);
        int imageHeight = imageHeight = bricks[0][0].getHeight(bR);
        for (int i = 0; i < bricks.length; i++)
            for ( int j =0; j < bricks[0].length; j++)
               g.drawImage(brick, i * imageWidth + 5, j* imageHeight + 5, bR);
    }
}

球类:

public class Ball {
    private int x=355 ;
    private int y=200;
    private int speed = 8;
    private int xVel = -speed;
    private int yVel = speed;
    private boolean gameOver = false;
    private Image ball;
    public Ball (Breakout bR){
        ball = bR.getImage(bR.getDocumentBase(),"ball.png");

    }
    public void update(Breakout bR, Paddle p){
       x += xVel;
       y += yVel;
       if (x < 0){
           xVel = speed;
        }
       else if (x > bR.getWidth()){
            xVel = -speed;
        }
       if(y > bR.getHeight()){
           gameOver = true;
        }
       else if (y < 0){
            yVel = speed;
        }
       collision(p);
    }
    public void collision(Paddle p){
        int pX = p.getX();
        int pY = p.getY();
        int pHeight = p.getImageHeight();
        int pWidth = p.getImageWidth();
        if (pX<=x && pX+pWidth>=x && pY-pHeight<=y && pY+pHeight>=y){
           yVel = -speed;
        }
    }
    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
    public void paint (Graphics g, Breakout bR){
        g.drawImage(ball,x,y,bR);
        if (gameOver){
            g.setColor(Color.WHITE);
            g.drawString("Game Over", 100,300);
        }
    }
}

感谢您的帮助:)

你可以

使用 Rectangle.intersects()。

为球类和砖类创建一个 getBounds() 方法。这将在实体周围创建一个虚拟矩形。

public Rectangle getBounds(){
    return new Rectangle(x, y, ballSizeX, ballSizeY);
}

然后检测碰撞将如下所示:

if(ball.getBounds().intersects(brick.getBounds())){
    doSomething();
}

如果需要,请在此处了解更多信息。

相关内容

  • 没有找到相关文章

最新更新