我想检测当rect遇到障碍物时(障碍物1和障碍物2,障碍物3现在没有添加)。我的障碍正随着路径的转变而移动。所有形状都是矩形。
提前谢谢!!
这是我的代码:
Rectangle rect= new Rectangle(100,225,50,125);
Rectangle obst1=new Rectangle(1200,300,30,50);
Rectangle obst2=new Rectangle(1200,300,91,51);
Rectangle obst3=new Rectangle(1200,300,20,50);
ImagePattern one = new ImagePattern(new Image("1.png"));
ImagePattern two = new ImagePattern(new Image("2.png"));
ImagePattern cactus1 = new ImagePattern(new Image("1cactus.png"));
ImagePattern cactus4 = new ImagePattern(new Image("4cactus.png"));
rect.setFill(one);`enter code here`
rect.setArcHeight(5);
rect.setArcWidth(5);
//rect.setFill(Color.VIOLET);
obst1.setFill(cactus1);
obst3.setFill(RED);
obst2.setFill(cactus4);
PathTransition path = new PathTransition();
path.setPath(l2);
path.setNode(obst1);
path.setDuration(Duration.millis(3000));
path.setCycleCount(Timeline.INDEFINITE);
path.setRate(-0.5);
//path.play();
PathTransition path2 = new PathTransition();
path2.setPath(l2);
path2.setNode(obst2);
path2.setDuration(Duration.millis(3000));
path2.setCycleCount(Timeline.INDEFINITE);
path2.setRate(-0.6);
//path2.play();
PathTransition path3 = new PathTransition();
path3.setPath(l2);
path3.setNode(obst2);
path3.setDuration(Duration.millis(3000));
path3.setCycleCount(Timeline.INDEFINITE);
path3.setRate(-0.3);
//path3.play();
int TimeLine=2;
Pane pane = new Pane();
pane.getChildren().add(obst1);
pane.getChildren().add(obst2);
//pane.getChildren().add(obst3);
pane.getChildren().add(rect);
pane.getChildren().add(l1);
Scene scene = new Scene(pane, 300, 250);
TranslateTransition tt = new TranslateTransition(Duration.millis(300));
tt.setFromY(00f);
tt.setToY(-100f);
tt.setCycleCount(TimeLine);
tt.setAutoReverse(true);
ParallelTransition pt = new ParallelTransition(rect, tt);
scene.setOnKeyPressed(e->
{
if(e.getCode()==KeyCode.UP)
{
pt.play();
}
if(e.getCode()==KeyCode.ESCAPE)
{
path.pause();
path2.pause();
path3.pause();
pt.pause();
}
if(e.getCode()==KeyCode.ENTER)
{
path.play();
path2.play();
path3.play();
pt.play();
}
});
EventHandler<ActionEvent> eventHandler = e ->
{
if(img==1)
{
rect.setFill(two);
img=2;
}
else
{
rect.setFill(one);
img=1;
}
};
Timeline animation = new Timeline(
new KeyFrame(Duration.millis(80), eventHandler));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
primaryStage.setTitle("Dinausor");
primaryStage.setScene(scene);
primaryStage.show();
答案 0 :(得分:0)
如果所有形状都是Rectangle
个对象,则可以使用intersects(...)
方法检查碰撞。这是一个例子:
Rectangle r1 = new Rectangle(0,0,100,100);
Rectangle r2 = new Rectangle(50,50,100,100);
System.out.println(r1.intersects(r2));// prints "true".