I am trying to detect the collision between an ImageView object and a Rectangle in javafx. The code below does not work and I'm not sure why. Nothing happens when the objects overlap each other. The original file of the image is a png if that makes a difference. The imageview object is moved with arrows and the rectangle is also moving with TranslateTranslation.
public void collision(ImageView a, Rectangle b) {
if (a.getBoundsInLocal().intersects(b.getBoundsInLocal())) {
b.setY(-100);
score++;
}
}
imageview movement code:
playg.setOnKeyPressed(new EventHandler<KeyEvent>(){
public void handle(KeyEvent event) {
if(event.getCode() == KeyCode.RIGHT) {
basket.setLayoutX(basket.getLayoutX() + 15);
brect.setLayoutX(basket.getLayoutX() + 15);
} else if (event.getCode() == KeyCode.LEFT) {
basket.setLayoutX(basket.getLayoutX() - 15);
brect.setLayoutX(basket.getLayoutX() - 15);
}
}
});
rectangle animation code:
TranslateTransition tt = new TranslateTransition(Duration.seconds(4), rect2);
tt.setByY(800f);
tt.setCycleCount(INDEFINITE);
tt.play();
Try using getBoundsInParent()
instead of getBoundsInLocal()
.
Some quick testing showed the BoundingBox
didn't change between two different positions when using local but did when using in-parent. I'm guessing this is due to the fact getBoundsInParent()
uses the transforms on the node (see the Javadoc between the two for more info).
However, I did not test if this effects the result of the intersecting method. Edit: Decided to do more tests. Adding two Rectangle
s to a StackPane
and moving one around showed that "local" always showed true and "in-parent" only showed true when visually intersecting. This is because, as far as "local" is concerned, the rectangles never left their starting positions which means they are technically intersecting at all times. But "in-parent" showed their true positions within the StackPane
.