[英]Collision detection between two images in java
I need to know when the rocket hit the meteor, img2 is the meteor and img is the rocket 我需要知道火箭何时击中流星,img2是流星,而img是火箭
g.drawImage(img, posX - img.getWidth(this)/2, posY - img.getHeight(this), this);
g.drawImage(img2,posX1 - img2.getWidth(this), posY1 - img2.getHeight(this),this);
System.out.println(posY-img.getWidth(this));
System.out.println(posY1);
}
public void colid (){
if (posY1+img.getWidth(this)>= posY-img2.getWidth(this) ){
System.out.println("teste");
}
You can create a Rectangle for every object like for a rocket or meteor 您可以为每个对象(例如火箭或流星)创建一个矩形
and there is a Rectangle method you can use 还有一个可以使用的矩形方法
boolean intersects(Rectangle r)
Determines whether or not this Rectangle and the specified Rectangle intersect.
so you could check 所以你可以检查一下
if (rectangleA.intersects(rectangleB){
System.out.println("Colliosion!!")
}
This should do it 这应该做到这一点
Rectangle r1 = new Rectangle(posX - img.getWidth(this)/2, posY - img.getHeight(this), img.getWidth(this), img.getHeight(this));
Rectangle r2 = new Rectangle(posX1 - img2.getWidth(this), posY1 - img2.getHeight(this), img2.getWidth(this), img2.getHeight(this));
boolean collision = r1.intersects(r2);
Note: You are dividing the width with 2 in the first image and not the second. 注意:您在第一张图像中将宽度除以2而不是第二张图像。 Maybe it is as it should be but just want to let you know if it is not.
也许它应该是它应该是但只是想让你知道它是不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.