java中的碰撞检测

时间:2016-06-07 00:55:19

标签: java graphics applet collision-detection

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

砖类:

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);
        }
    }
}

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

您可以使用Rectangle.intersects()。

为ball和brick类创建一个getBounds()方法。这将创建一个围绕实体的虚拟矩形。

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

然后检测到碰撞看起来像:

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

如果您需要,请提供更多信息here