Rafsun Chowdhury
Rafsun Chowdhury

Reputation: 161

JavaFx Shape Intersect always returns false/true

So, I have created 2 Rectangle Shape and checking if they are intersecting but getting different results each time :

    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

Upvotes: 1

Views: 444

Answers (1)

BinderNews
BinderNews

Reputation: 560

It's because you're mixing layoutX and layoutY with x and y. If you run the following code (I modified your original code and added some print statements) you'll see that although you're changing layoutX and layoutY when you call a.intersects(b.getLayoutX(), ...) it's testing if a which is at (0,0) and has size (10,10) intersects with a rectangle at (100,100) and the answer is, of course, no.

Instead of using setLayoutX and getLayoutX (or Y) just use setX/getX and 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
}

Upvotes: 1

Related Questions