0

我有一个由用户在屏幕上绘制的充满矩形的结构,旨在作为球在运行时反弹的“障碍”。我考虑过使用,但意识到(除非我不够了解)当返回 trueRectangle.intersects()时,没有办法判断球的走向。intersects目前,我正在使用大量逻辑来尝试检测球何时接触给定矩形的边缘,并且它根本无法正常工作。如果有更好的方法来做到这一点,或者如果有办法修复下面的逻辑,我愿意听取任何建议。谢谢!

for (Rectangle rect : r)
    {
      int rx = rect.x;
      int ry = rect.y;
      int rh = rect.height;
      int rw = rect.width;
      //If the ball hits either side of the rectangle, change the x direction
      if((loc.x > rx && loc.x > ry && loc.x < (ry + rh))||(loc.x < (rx + rw) && loc.x > rx && loc.x <(ry + rh)))
        {dx *= -1;}
      //If the ball hits either the top or bottom, change the y direction
      if((loc.y > ry && loc.y > rx && loc.y < (rx + rw))||(loc.y < (ry + rh) && loc.y > ry && loc.y <(rx + rw)))
        {dy *= -1;}
    }

作为参考,并使其更具可读性,r 是包含所有绘制矩形的向量,loc 是球当前所在的点,dx 和 dy 是球移动的方向(1 或 -1)。

4

0 回答 0