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).