【发布时间】:2018-10-13 01:39:44
【问题描述】:
我正在使用时间线为线条设置动画,但我无法检测到碰撞。 这是我基本上要尝试做的一个简短示例。
Line line = new Line(100, 200, 200, 200);
Line line1= new Line(350,50,350,300);
Timeline animation = new Timeline(
new KeyFrame(Duration.seconds(1.5), new KeyValue(line.endXProperty(), 400))
);
animation.setCycleCount(1);
animation.play();
if(line.getBoundsInParent().intersects(line1.getBoundsInParent())){
System.out.println("Collision!");
}
Pane root = new Pane(line);
root.getChildren().add(line1);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
我使用了我在 stackoverflow 中找到的一些其他代码、方法和想法。像下面这样一个:
Bounds bounds = line.getLayoutBounds();
Shape intersect = Shape.intersect(line, line1);
boolean intersects = intersect.getBoundsInLocal().getWidth() != -1;
System.out.println("Intersects: " + intersects);
if(intersect.getBoundsInLocal().getWidth() != -1)
{
System.out.println("This object can overlap other the other object!");
System.out.print("Collision detected!");
}
else
{
intersect.getBoundsInLocal().getWidth();
System.out.print("Collision not detected!");
}
还有这段代码的一些变体。
任何想法都会有所帮助
【问题讨论】:
-
这里的“碰撞”是什么意思?线段相交?这些线永远不会相交:第一条总是在
x=200的左边,第二条总是在x=350的右边。 -
是的,我的意思是相交。实际上,由于动画,线条正在移动。我执行了它。
-
啊,好吧,我看错了哪条线是动画的。你不能只计算它们相交的时间吗?似乎这将是基本的几何形状......
-
您只在动画开始前检查交叉点。如果要动态检查,则需要在动画期间调整的属性以及检查所依赖的属性中添加监听器。 (在本例中为
boundsInParent属性。)
标签: animation javafx javafx-8 collision-detection