javafx collision issue between path(line) with thick stroke and circle

1.2k views Asked by At

I am using JavaFx 8 library.

My task is simple: I want to check if circle collides with a path that has a thick stroke around it. The problem is that both functions Path.intersect() and Shape.intersect() ignores the stroke around a path/line.

Path tempPath = new Path(player.getPath().getElements());
//player.getDot() is Circle
if(tempPath.intersects(player.getDot().getBoundsInParent())){
   Shape intersect = Shape.intersect(tempPath, player.getDot());
   if(intersect.getBoundsInLocal().getWidth() != -1){
      System.out.println("Path Collision occurred"); 
   }
}

My path is made out of many LineTo objects. The format is this:

/** Creates path and player dot */
private void createPath() {
    this.path = new Path();
    this.path.setStrokeWidth(20);
    this.path.setStroke(Color.RED);
    this.path.setStrokeLineCap(StrokeLineCap.ROUND);
    this.path.setStrokeLineJoin(StrokeLineJoin.ROUND);

    this.dot = new Circle(10, Color.BLUE);
    this.dot.setOpacity(1);
}

How could I implement a successful collision detection?

1

There are 1 answers

1
Roland On BEST ANSWER

The collision detection works just fine:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.ClosePath;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Shape;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
import javafx.stage.Stage;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {

        BorderPane root = new BorderPane();

        Circle circle = new Circle(100, 100, 30);
        Path path = new Path();

        double x = 144;

        path.getElements().add(new MoveTo(x, 140));
        path.getElements().add(new LineTo(500, 100));
        path.getElements().add(new ClosePath());

        path.setStrokeWidth(60);
        path.setStrokeLineCap(StrokeLineCap.ROUND);
        path.setStrokeLineJoin(StrokeLineJoin.ROUND);

        Shape shape = Shape.intersect(circle, path);

        boolean intersects = shape.getBoundsInLocal().getWidth() != -1;

        System.out.println("Intersects: " + intersects);

        Pane pane = new Pane();
        pane.getChildren().addAll(circle, path);
        root.setCenter(pane);

        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

Switch x = 144 with x = 145 for testing. The console shows whether there's an intersection or not.

The problem you have is that you're comparing different bounds.

See the documentation of Node, section "Bounding Rectangles" about how the various bounds are calculated.