【发布时间】:2014-11-29 23:51:29
【问题描述】:
我的任务是有一个用于添加随机位置和方向的球的按钮。我无法检查球之间的碰撞。问题出在第 123 行。谢谢!
import java.util.ArrayList;
import java.util.Scanner;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
class BallPane extends Pane {
private double radius = 10;
private ArrayList<Ball> list = new ArrayList();
private Timeline animation;
public BallPane() {
Scanner kb = new Scanner(System.in);
System.out.println("\nPlease press RIGHT and LEFT arrow keys to increase and decrease"
+ " the speed of the balls.");
animation = new Timeline(
new KeyFrame(Duration.millis(50), (ActionEvent e) -> {
moveBall();
}));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play(); // Start animation
}
public void addBall() {
Ball balls = new Ball(BallPane.this);
getChildren().add(balls.getCircle());
list.add(balls);
}
public void moveBall() {
double x, y, dx, dy;
// Check boundaries
Ball a;
for (int i = 0; i < list.size(); i++) {
a = list.get(i);
x = a.getCircle().getCenterX();
y = a.getCircle().getCenterY();
dx = a.getDirectionX() + (int) Math.random() * 100;
dy = a.getDirectionY() + (int) Math.random() * 100;
if (x < a.getCircle().getRadius()
|| x > getWidth() - a.getCircle().getRadius()) {
dx *= -1; // Change ball move direction
}
if (y < a.getCircle().getRadius()
|| y > getHeight() - a.getCircle().getRadius()) {
dy *= -1; // Change ball move direction
}
// Adjust ball position
x += dx;
y += dy;
a.setDirectionX(dx);
a.setDirectionY(dy);
a.getCircle().setCenterX(x);
a.getCircle().setCenterY(y);
// Ball b = list.get(i + 1);
}
//line 123
//also trying to use the distance formula to check the distance between two circles' center points
for (int i = 0; i < Timeline.INDEFINITE; i++) {
if (Math.sqrt(Math.pow(list.get(i).getCenterX()
- list.get(i + 1).getCenterX(), 2) + Math.pow(list.get(i).getCenterY()
- list.get(i + 1).getCenterY(), 2)) <= 2 * radius) {
list.get(i).getCircle();
getChildren().remove(i);
list.remove(i);
}
}
}
}//End of BallPane class.
感谢您的帮助!主要是代码堆栈溢出......你为什么让我输入 this.asdl;kfj dsal;kf jldfjals ;kdjfldksajf l;askfj
【问题讨论】:
-
你为什么使用
i < Timeline.INDEFINITE作为你的循环条件? -
...似乎只检查列表中相邻的球是否发生碰撞......但我猜任何组合都必须检查......
-
@James_D 我正在使用时间线 indefenite 因为如果我将它设置为 list.size() 它会超出范围......而 Jens-Peter ......我将如何解决这个问题?