javafx粗笔画路径(线)与圆之间的碰撞问题

标签 java javafx collision-detection intersect stroke

我正在使用 JavaFx 8 库。

我的任务很简单:我想检查圆是否与周围有粗笔划的路径碰撞。问题是 Path.intersect() 和 Shape.intersect() 函数都会忽略路径/线周围的笔划。

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"); 
   }
}

我的路径由许多 LineTo 对象组成。 格式是这样的:

/** 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);
}

如何实现成功的碰撞检测?

最佳答案

碰撞检测工作得很好:

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);
    }
}

将 x = 144 切换为 x = 145 进行测试。控制台显示是否有交叉点。

您遇到的问题是您正在比较不同的界限。

请参阅 Node 的文档,“边界矩形”部分介绍了如何计算各种边界。

关于javafx粗笔画路径(线)与圆之间的碰撞问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30705426/

相关文章:

css - 没有颜色选择器的 JavaFX 颜色选择器

java - 从哪里获得 JavaFX 源代码?

c++ - 简单的碰撞检测

hash - 通过_brute force_破坏单向哈希属性和证明碰撞之间的区别

algorithm - 找到最接近某个位置的非碰撞矩形的有效方法是什么

java - 在运行时用 Java 创建 n 维数组

java - org.apache.http 已弃用,该使用什么?

java - JPA EntityManager 大内存问题

java - 将原语插入 List 时会出现编译或运行时错误吗?

Javafx 使用计时器时不在 fx 应用程序线程上