我目前正在研究JavaFX与不同形状之间的边界相交。 我想检测两个多边形在其点上的碰撞,而不是它们的边界(即2个多边形)。JavaFX十字形状与多边形
请参阅图1:不需要的行为,图2:所需的行为。
是否有任何现有的算法来帮助我或任何图书馆使用? 感谢提前:)
在这里找到我的解决办法:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
public class Tester extends Application {
@Override
public void start(Stage stage) throws Exception {
Pane root = new Pane();
root.setStyle("-fx-background-color:cyan;");
Polygon p1 = new Polygon();
p1.getPoints().addAll(new Double[]{
50.,50.,
50.,100.,
60.,100.,
60.,80.,
80.,70.,
80.,100.,
100.,100.,
100.,50.
});
p1.setFill(Color.GREEN);
Polygon p2 = new Polygon();
p2.getPoints().addAll(new Double[]{
65.,100.,
65.,90.,
75.,80.,
100.,100.
});
p2.setFill(Color.RED);
root.getChildren().addAll(p1,p2);
stage.setScene(new Scene(root));
stage.show();
Shape inter = Shape.intersect(p1, p2);
root.getChildren().add(inter);
System.out.println(inter.getLayoutBounds().getWidth() + ":" + inter.getLayoutBounds().getHeight());
if(inter.getLayoutBounds().getHeight()<=0 || inter.getLayoutBounds().getWidth()<=0) {
System.out.println("No intersection");
}
else {
System.out.println("intersection detected");
}
}
public static void main(String[] args) {
launch(args);
}
}
输出:
20.0:16.0 intersection detected
它似乎正常工作,我将用Path对象进行测试以替换Polygon对象。
你可能要检查,如果你的一个多边形的边的交点是在其他的边界。使用:'mypolygon1.getBoundsInLocal()。contains(myPolygon2.getBoundsInLocal())' – Aspirant
[检查形状与JavaFX的碰撞]的可能的重复(http://stackoverflow.com/questions/15013913/checking-collision-of-shapes -with-javafx) – jewelsea
@user我测试过,但它是图1的情况。 – PacDroid