Search code examples
javajavafxjavafx-2collision-detectionjavafx-8

How to achieved collision detection in Translate Transition (in JavaFX)?


I have written the below JavaFX program in which two rectangle nodes are in translate transition:

public class Test extends Application{
public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    BorderPane borderPane = new BorderPane();
    borderPane.setStyle("-fx-background-color: green;");


    Rectangle rect1 = new Rectangle(20,20,50, 50);
    rect1.setArcHeight(15);
    rect1.setArcWidth(15);
    rect1.setFill(Color.RED);

    Rectangle rect2 = new Rectangle(20,20,30, 30);
    rect2.setArcHeight(15);
    rect2.setArcWidth(15);
    rect2.setFill(Color.RED);

    TranslateTransition translateTransition1 = new TranslateTransition(Duration.millis(2000), rect1);
    translateTransition1.setFromX(0);
    translateTransition1.setToX(300);
    translateTransition1.setToY(300);
    translateTransition1.setCycleCount(Timeline.INDEFINITE);
    translateTransition1.setAutoReverse(true);
    translateTransition1.play();

   TranslateTransition translateTransition2 = new TranslateTransition(Duration.millis(2000), rect2);
   translateTransition2.setFromX(300);
   translateTransition2.setToX(0);
   translateTransition2.setToY(300);
   translateTransition2.setCycleCount(Timeline.INDEFINITE);
   translateTransition2.setAutoReverse(true);
   translateTransition2.play();


    borderPane.getChildren().add(rect1);
    borderPane.getChildren().add(rect2);

    primaryStage.setScene(new Scene(borderPane, 500, 500));
    primaryStage.show();

  }

}

How can I implement collision detection of the two rectangle nodes which are in Translate Transition?


Solution

  • With rectangles it's pretty easy; just get their bounds in the parent and see if they intersect. The only drawback with this is it doesn't take into account the curved corners: you may need to compute that by hand if you want that level of accuracy. For non-rectangular shapes you can also just observe the bounds in parent properties, but you'd need to do the computation by hand to see if the shapes intersect.

        ObservableBooleanValue colliding = Bindings.createBooleanBinding(new Callable<Boolean>() {
    
            @Override
            public Boolean call() throws Exception {
                return rect1.getBoundsInParent().intersects(rect2.getBoundsInParent());
            }
    
        }, rect1.boundsInParentProperty(), rect2.boundsInParentProperty());
    
        colliding.addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> obs,
                    Boolean oldValue, Boolean newValue) {
                if (newValue) {
                    System.out.println("Colliding");
                } else {
                    System.out.println("Not colliding");
                }
            }
        });