How to implement collision detection on nodes which are in StackPane (in JavaFX)?

collision-detection, javafx, javafx-2, javafx-8

Solution

In your test condition you compare the local bounds of one rectangle with the bounds in parent of the other rectangle. You want to compare the same bounds types.

So change:

rect1.intersects(newValue)

To:

rect1.getBoundsInParent().intersects(newValue)

To understand bounds types better, you might want to play with this intersection demo application.

Problem

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.

Original source

Related problems