i making breakout game. have 2 class: brick class displays array of brick images , ball class moves ball image around window. i'm trying figure out how make brick disappear when ball hits 1 of brick. appreciated.
brick class:
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 =0; < 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); (int = 0; < bricks.length; i++) ( int j =0; j < bricks[0].length; j++) g.drawimage(brick, * imagewidth + 5, j* imageheight + 5, br); } }
ball class:
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); } } }
thanks :)
you can use rectangle.intersects().
create getbounds() method both ball , brick classes. create virtual rectangle surrounding entities.
public rectangle getbounds(){ return new rectangle(x, y, ballsizex, ballsizey); }
then detecting collision like:
if(ball.getbounds().intersects(brick.getbounds())){ dosomething(); }
more info here if need it.