1

我正在做一个小练习,我必须初始化一个以随机速度在屏幕上移动的球对象数组。当它们相互碰撞时,我需要球反转速度。问题是我只能将每个球与自己进行比较,以便它们不断“相交”并来回晃动。我很好地感觉问题出在下面的 if 语句中,因为我将 balls[i] 与 balls[i] 进行比较,其中“i”同时是相同的数字。当我通过 intersect 函数传递 balls[i] 时,我需要将每个元素与除自身之外的所有其他元素进行比较。我尝试了几种方法,但它们没有用,而且是多余的。

//draw()中的for循环

   for(int i = 0; i < balls.length; i++){
    //balls[i].drawBalls();
    //balls[i].moveBalls();
    ***if (balls[i].intersect(balls[i])) {
        balls[i].moveIntersectingBalls();
    }***
  }

//球相交方法

boolean intersect(Ball b) {
    float distance = dist(bXpos,bYpos,b.bXpos,b.bYpos);

    if (distance < bRadius + b.bRadius) {
      return true;
    } else {
      return false;
    }
  }

//如果相交方法球移动

void moveIntersectingBalls(){
    bXspd *= -1;
    bYspd *= -1;
  }
4

3 回答 3

1

To compare each ball with all the other balls, you need two for loops:

for (int i = 0; i < balls.length; i++)
{
    for (int j = 0; j < balls.length; j++)
    {
        // Check first that you are not comparing a ball to itself.
        if (i != j)
            if (balls[i].intersect(balls[j]))
                balls[i].moveIntersectingBalls();
    }
}
于 2013-09-22T22:38:44.123 回答
0

I mean, this code doesn't seem to make much sense:

if (balls[i].intersect(balls[i])) {
    balls[i].moveIntersectingBalls();
}

But you pointed that out yourself I think.

Are you looking for something like:

for(int i = 0; i < balls.length; i++){
    for(int j = (i+1); j < balls.length; j++){
        if (balls[i].intersect(balls[j])) {
            balls[i].moveIntersectingBalls();
            // Maybe also add:
            balls[j].moveIntersectingBalls();
        }
    }
}

You can start the inner loop at i instead of 0 because you've already "checked" those previously.

In fact, if you start it at 0, you will check each ball-pair twice (e.g. (1,3) and again at (3,1)) perhaps causing the twitching you've described.

于 2013-09-22T22:37:17.993 回答
-1

你需要的是一个双循环:

        for(int i = 0; i < balls.length; i++){
        for(int j = 0; j < balls.length; j++){
            if (balls[i].intersect(balls[j]) && i != j) {
                balls[i].moveIntersectingBalls();
            }
        }
    }

使用双循环,您将每个球(第一个循环)与所有其他球(第二个循环)进行比较,如果您击中一个,则调用 moveIntersecingBalls(); 第一个球。

这个算法可能会被优化,因为当两个球发生碰撞时,再次检查它们是没有用的,但这是一个好的开始。

于 2013-09-22T22:36:44.537 回答