2016-06-07 201 views
0

我在做一個突破遊戲。我有兩個班級:一個磚塊類,它顯示一系列磚塊圖像和一個可在窗口周圍移動球圖像的球類。我試圖弄清楚當球擊中某塊磚時如何使磚消失。任何幫助將不勝感激。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); 
    } 
} 

Ball類:

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

1)爲什麼要編寫一個小程序?如果是由於老師指定它,請將它們轉介給[爲什麼CS教師應該停止**教Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should -stop教學-java的小應用程序/)。 2)爲了更快地獲得更好的幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 3)另請參見[使用複雜形狀的碰撞檢測](http://stackoverflow.com/a/14575043/418556)瞭解一個工作示例(使用Java-2D形狀)。 –

+1

順便說一句 - 這是使用AWT或Swing組件嗎? –

+1

[複雜形狀的碰撞檢測]可能的重複(http://stackoverflow.com/questions/14574045/collision-detection-with-complex-shapes) –

回答

0

您可以使用Rectangle.intersects()。

爲你的球類和磚類創建一個getBounds()方法。這會在您的實體周圍創建一個虛擬矩形。

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

然後檢測碰撞會是什麼樣子:

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

更多信息here如果你需要它。