[英]collision detection in java
I am making a Breakout game. 我正在制作突破游戏。 I have two class: a brick class which displays an array of brick images and a ball class which moves an ball image around the window.
我有两个类:显示砖块图像数组的砖块类和在窗口周围移动球形图像的球类。 I'm trying to figure out how to make the brick disappear when the ball hits one of the brick.
我试图弄清楚当球碰到一块砖时如何使砖消失。 Any help would be greatly 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 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 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 for your help :) 谢谢你的帮助 :)
You can use Rectangle.intersects(). 您可以使用Rectangle.intersects()。
Create a getBounds() method for both your ball and brick classes. 为您的球类和砖类创建一个getBounds()方法。 This will create a virtual rectangle surrounding your entities.
这将在您的实体周围创建一个虚拟矩形。
public Rectangle getBounds(){
return new Rectangle(x, y, ballSizeX, ballSizeY);
}
Then detecting a collision would look like: 然后检测到碰撞将类似于:
if(ball.getBounds().intersects(brick.getBounds())){
doSomething();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.