所以,我创建了2个矩形形状并检查它们是否相交但每次都得到不同的结果:
Rectangle a = new Rectangle( 10.00, 10.00 );
Rectangle b = new Rectangle( 30.00, 20.00 );
a.setFill(Color.RED);
_centerPane.getChildren().add(a);
_centerPane.getChildren().add(b);
//both at 0.00
System.out.println( a.intersects( b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight()) ); //true
System.out.println( b.intersects( a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight()) ); //true
a.setLayoutX( 100.00);
a.setLayoutY(100.00);
//only a at different position and not visually intersecting
System.out.println( a.intersects( b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight()) ); //true
System.out.println( b.intersects( a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight()) ); //false
b.setLayoutX( 73.00);
b.setLayoutY(100.00);
//Now b is set near a and intersects a visually
System.out.println( a.intersects( b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight()) ); //false
System.out.println( b.intersects( a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight()) ); //false
答案 0 :(得分:1)
这是因为您将layoutX
和layoutY
与x
和y
混合在一起。如果您运行以下代码(我修改了您的原始代码并添加了一些打印语句),您会看到虽然您在调用layoutX
时正在更改layoutY
和a.intersects(b.getLayoutX(), ...)
,但它正在测试位于(0,0)并且大小(10,10)的a
与(100,100)处的矩形相交,答案当然是否。
不要使用setLayoutX
和getLayoutX
(或Y
),而只需使用setX
/ getX
和setY
/ getY
public static void test(Rectangle a, Rectangle b) {
System.out.println( a.intersects( b.getLayoutX(), b.getLayoutY(), b.getWidth(), b.getHeight()) );
System.out.println( b.intersects( a.getLayoutX(), a.getLayoutY(), a.getWidth(), a.getHeight()) );
}
public static void print(String name, Rectangle r) {
System.out.println(name + " : " + r.toString() + " layoutX: " + r.getLayoutX() + " layoutY: " + r.getLayoutY());
}
public static void main(String[] args) {
Rectangle a = new Rectangle( 10.00, 10.00 );
Rectangle b = new Rectangle( 30.00, 20.00 );
//both at 0.00
print("a", a);
print("b", b);
test(a, b); // true, true
a.setLayoutX(100.00);
a.setLayoutY(100.00);
//only a at different position and not visually intersecting
print("a", a);
print("b", b);
test(a, b); // true, false
b.setLayoutX( 73.00);
b.setLayoutY(100.00);
//Now b is set near a and intersects a visually
print("a", a);
print("b", b);
test(a, b); // false, false
}