我有这个数组
Ball[] balls = new Ball[7]; // 7 just being an example
在我的 Ball 类中,我有 x 和 y 值的 getter 和 setter。 我正在尝试比较 x 和 y 值以确保它们不相交。
我的第一个想法是制作一个看起来像这样的循环
for(Ball b1 : balls) {
for(Ball b2 : balls) {
if(b1.intersects(b1, b2)) {. . .} // I made intersects, not my issue
}
}
但这并不好,因为它比较:
- 球 0 到球 0
- 球 1 到球 1
等等
for(int i = 0; i < balls.length; i++) { System.out.println(f.getContentPane().getWidth() + "\n" + f.getContentPane().getHeight()); int radius = 10 + rand.nextInt(20); balls[i] = new Ball(360, radius, rand.nextInt(f.getContentPane().getWidth() - 4 * radius - 5) + radius + 5, rand.nextInt(f.getContentPane().getHeight() - 4 * radius - 5) + radius + 5 ); } for(Ball b1 : balls) { for (Ball b2 : balls) { while (b1.intersects(b1, b2)) { System.out.println("Ball started out inside of another, replacing now."); b1.setX(rand.nextInt(f.getContentPane().getWidth() - 2 * b1.getRadius() - 5) + b1.getRadius() + 5); b1.setY(rand.nextInt(f.getContentPane().getHeight() - 2 * b1.getRadius() - 5) + b1.getRadius() + 5); } } }
//////////////类更改///////////////////
class Ball {
private int direction;
private int radius;
private int x,y;
Ball(int direction, int radius, int x, int y) {
this.direction = direction;
this.radius = radius;
this.x = x;
this.y = y;
}
// Getters + Setters here
boolean intersects(Ball b1, Ball b2) {
double x = Math.pow((b2.getX() - b1.getX()), 2); // Distance formula
double y = Math.pow((b2.getY() - b1.getY()), 2); // Distance formula
double r = b1.getRadius() + b2.getRadius();
//System.out.println(x + " + " + y + " <= " + r );
return x + y <= r;
}
}
(请忽略我没有将第一 block 代码放入方法和类中,我已经在实际代码中做到了这一点。)
无论出于何种原因,我想不出一种没有大量 if 语句的方法来做到这一点
(所以我要求最好的方法来做到这一点)
最佳答案
比较每对不同(即没有球与其本身)的 Ball
的一种方法,而不需要多次比较任何对:
for (int i = 0; i < balls.length; ++i) {
Ball b1 = balls[i];
for (int j = i+1; j < balls.length; ++j) {
Ball b2 = balls[j];
if (b1.intersects(b1, b2)) {
// ...
}
}
}
检测在解决先前碰撞的过程中引入的新碰撞仅意味着对球
进行多次传递,直到不再发生任何碰撞。一个简单的,也许是幼稚的方法是这样的:
boolean foundCollision;
int numTries = 0;
int maxTries = 1000000;
do {
foundCollision = false;
for (int i = 0; i < balls.length; ++i) {
Ball b1 = balls[i];
for (int j = i+1; j < balls.length; ++j) {
Ball b2 = balls[j];
if (b1.intersects(b1, b2)) {
foundCollision = true;
// resolve collision...
}
}
++numTries;
} while (foundCollision && numTries < maxTries);
if (numTries >= maxTries)
System.err.println("Couldn't sort out balls after " + maxTries + "tries: what now?");
关于java - 如何在不检查相同内容的情况下检查一个数组中的值是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54191877/