当两个矩形正确相交时,此代码不显示:
public boolean intersects(Entity other) {
hitbox.setBounds((int) x, (int) y, (int) width, (int) height);
System.out.println(x);
System.out.println(y);
System.out.println(width);
System.out.println(height);
boolean a = false;
Point b = new Point();
Point c = new Point();
Point d = new Point();
Point e = new Point();
b.setLocation((int)other.getX(), (int)other.getY());
c.setLocation((int)other.getX() + (int)other.getWidth(), (int)other.getY());
d.setLocation((int)other.getX() + (int)other.getWidth(), (int)other.getY() + (int)other.getHeight());
e.setLocation((int)other.getX(), (int)other.getY() + (int)other.getHeight());
if(hitbox.contains(b)){a = true;}
if(hitbox.contains(c)){a = true;}
if(hitbox.contains(d)){a = true;}
if(hitbox.contains(e)){a = true;}
return a;
}
开始时它报告矩形相交,但实际上并没有,然后突然拒绝接受它们相交,即使它们相交。
最佳答案
您的代码不起作用,因为矩形交集不要求一个矩形的角位于另一个矩形内。这可能会导致漏报,即相交的矩形得到 false
。
.
另一种获得假阴性的方法是当你的 hitbox
的两个或四个角在 other
矩形内时:因为你只用一种方式检查它,而不是换句话说,这种交叉路口也不会被发现。
您不必使用任何系统类来确定矩形是否相交。你可以这样做:
boolean intersectRect(int x1, int y1, int w1, h1, int x2, int y2, int w2, int h2) {
return intersectRange(x1, x1+w1, x2, x2+w2)
&& intersectRange(y1, y1+h1, y2, y2+h2);
}
boolean intersectRange(int ax1, int ax2, int bx1, int bx2) {
return Math.max(ax1, bx1) <= Math.min(ax2, bx2);
}
关于java - 为什么这个相交功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20432258/