I am trying to check collision detection on the nodes which are inside StackPane. Below is my code:
public void start(Stage primaryStage) throws Exception {
StackPane pane = new StackPane();
Scene scene = new Scene(pane,300,300,Color.GREEN);
primaryStage.setScene(scene);
primaryStage.show();
Rectangle rect1 = new Rectangle(50, 50);
rect1.setFill(Color.BLUE);
Rectangle rect2 = new Rectangle(50, 50);
pane.getChildren().add(rect1);
pane.getChildren().add(rect2);
TranslateTransition translateTransitionEnemyCar = new TranslateTransition();
translateTransitionEnemyCar.setDuration(Duration.millis(2000));
translateTransitionEnemyCar.setNode(rect2);
translateTransitionEnemyCar.setFromY(-150);
translateTransitionEnemyCar.setToY(150);
translateTransitionEnemyCar.setAutoReverse(true);
translateTransitionEnemyCar.setCycleCount(Timeline.INDEFINITE);
translateTransitionEnemyCar.play();
checkCollision(pane,rect1,rect2);
}
//Collision Detection
void checkCollision(StackPane pane, final Rectangle rect1, Rectangle rect2){
rect2.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {
@Override
public void changed(ObservableValue<? extends Bounds> arg0,Bounds oldValue, Bounds newValue) {
if(rect1.intersects(newValue)){
System.out.println("Collide ============= Collide");
}
}
});
}
}
Here the collision detection is working if I use AnchorPane. But with StackPane I am not able to achieve it. I guess it is because of the co-ordinate system of the stack pane (Correct me if I am wrong).
So please help me out to achieve collision detection of the above two rectangles. Also please provide some suggestion (if you know) to implement such collision detection on nodes inside StackPane if I want to change the the co-ordinate of the nodes.