我正在制作游戏,只需点击鼠标就可以从底部中心带上彩色球。我根据球的颜色(圆圈)创建了类。我正在使用Pane并使用路径转换来移动球。但我想检测现有的每个新移动球的碰撞(已经添加到窗格中的球)。到目前为止,我找不到一种方法来检测它。怎么做?我做了两个清单。一个包含添加的球,另一个包含每个新球来自的总球。
球类
public class Ball extends Circle{
private String color;
public Ball(String color){
this.color = color;
}
public String getColor() {
return color;
}
}
每种不同颜色的球......
public class BlueBall extends Ball{
private Image imgBlueBall =
new Image("/resources/blue.png");
public BlueBall() {
super("blue");
ImagePattern bluePattern = new ImagePattern(imgBlueBall);
setFill(bluePattern);
setRadius(20);
}
}
就像RedBall,GreenBall等..
这是应用程序类
public class BallGameExe extends Application{
private Pane root = new Pane();
private boolean isIntersected;
private static List<Ball> ballsList = new ArrayList<>();
private ArrayList<Ball> addedBallsList = new ArrayList<>();
private int index = 0;
@Override
public void start(Stage primaryStage) throws Exception {
makeBallsList();
root.setId("root");
Path path = new Path();
path.setStroke(Color.TRANSPARENT);
MoveTo moveTo = new MoveTo();
moveTo.setX(400.0f);
moveTo.setY(600.0f);
root.setOnMouseClicked( e -> {
LineTo lineTo = new LineTo();
lineTo.setX(e.getX());
lineTo.setY(e.getY());
Ball ball = ballsList.get(index);
PathTransition pt = new PathTransition();
pt.setDuration(Duration.millis(2000));
pt.setNode(ball);
pt.setPath(path);
LineTo lineTo2 = new LineTo();
if(e.getX() < 20 ){
lineTo2.setX((780 - e.getX()) - (800 - e.getY()));
lineTo2.setY(0);
path.getElements().clear();
path.getElements().add(moveTo);
path.getElements().add(lineTo);
path.getElements().add(lineTo2);
pt.setPath(path);
pt.play();
root.getChildren().remove(path);
root.getChildren().add(path);
root.getChildren().add(ball);
addedBallsList.add((Ball) ball);
}else if( e.getX() > 780){
lineTo2.setX((e.getX() - 20) - (e.getY() - 0));
lineTo2.setY(0);
path.getElements().clear();
path.getElements().add(moveTo);
path.getElements().add(lineTo);
path.getElements().add(lineTo2);
pt.setPath(path);
pt.play();
root.getChildren().remove(path);
root.getChildren().add(path);
root.getChildren().add(ball);
addedBallsList.add((Ball) ball);
}else {
path.getElements().clear();
path.getElements().add(moveTo);
path.getElements().add(lineTo);
pt.setPath(path);
pt.play();
root.getChildren().remove(path);
root.getChildren().add(path);
root.getChildren().add(ball);
addedBallsList.add((Ball) ball);
}
index++;
});
Scene scene = new Scene(root, 800, 600);
scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm());
primaryStage.setTitle("BubblesGridPane");
primaryStage.setScene(scene);
primaryStage.show();
}
我有另一种方法,基本上创建一个200个球的数组,并使其随机。因为我计划在每个级别有不同级别的200个球。这个方法填充了ArrayList ballsList。