我正在使用时间轴来制作动画线,但我无法检测到碰撞。 这是我基本上要做的一个简短的例子。
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!");
}
此代码的一些变化。
任何想法都会有所帮助
答案 0 :(得分:0)
在这种情况下,“碰撞”(第一次线相交)是line.endX
达到350时。
所以你可以这样做:
BooleanBinding intersecting = line.endXProperty().greaterThanOrEqualTo(350);
intersecting.addListener((obs, wasIntersecting, isNowIntersecting) -> {
System.out.println("Collision!");
});
即:
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.binding.BooleanBinding;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;
public class AnimatedLine extends Application {
@Override
public void start(Stage primaryStage) {
Line line = new Line(100, 200, 200, 200);
Line line1= new Line(350,50,350,300);
BooleanBinding intersecting = line.endXProperty().greaterThanOrEqualTo(350);
intersecting.addListener((obs, wasIntersecting, isNowIntersecting) -> {
System.out.println("Collision!");
});
Timeline animation = new Timeline(
new KeyFrame(Duration.seconds(1.5), new KeyValue(line.endXProperty(), 400))
);
animation.setCycleCount(1);
animation.play();
Pane root = new Pane(line);
root.getChildren().add(line1);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
一般来说,检测两个线段是否相交可能比一个水平线和一个垂直线更难一点,但是你总是可以很容易地解决方程并做类似的事情。