0

I have a structure full of rectangles that are drawn on the screen by the user, meant to be "blockades" for a ball to bounce off of during runtime. I considered using Rectangle.intersects(), but realized that (unless I'm not well enough informed) there isn't a way to tell which way the ball was going when intersects returns true. Currently I'm using this large mess of logic to try and detect when the ball touches the edges of a given rectangle, and its not working well at all. If there is a better way to do this, or if there is a way to fix the logic below, I'm open to hear any suggestions with this. Thank you!

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;}
    }

For reference, and to make this a bit more readable, r is a Vector containing all drawn rectangles, loc is a Point where the ball currently is, and dx and dy are the direction the ball is moving (either 1 or -1).

zakparks31191
  • 919
  • 2
  • 21
  • 42
  • 2
    I just banged my head against a very large wall offer a simular question, go check out [this](http://stackoverflow.com/questions/13261767/java-ball-object-doesnt-bounce-off-of-drawn-rectangles-like-its-supposed-to/13263022#13263022) – MadProgrammer Nov 07 '12 at 04:15
  • Holy smokes, +1 for that – zakparks31191 Nov 07 '12 at 05:18

0 Answers0