Sorry for the awful title. The purpose of the Java applet is as such: A ball is bouncing around the screen. The size and speed of this ball can be changed via scrollbars. The user can press and drag the mouse on the screen to draw rectangles. The ball will bounce off of these rectangles as well. The bounds of these rectangles are stored in a vector. When a rectangle is clicked, it (and all other rectangles at that point) are removed from the vector (and the screen).
The problem I’m having is two-fold: One, when I click a rectangle to remove it, it doesn’t get removed, but that can be solved later.
Two: The ball doesn’t bounce off of the rectangles like it’s supposed to. When I draw a rectangle in either the same row or column as the ball, the ball bounces around inside of a tiny rectangle, like it’s stuck.
Here’s my code to detect if the ball is hitting the boundaries of either the applet or any of the rectangles:
public void move()
{
//if it will hit the right or left boundary, flip the x direction and set it
if (loc.x+size >= boundx || loc.x <= 0)
{ dx *= -1; }
//if it will hit the top or bottom boundray, flip the y direction and set it
if (loc.y+size >= boundy || loc.y <= 0)
{ dy *= -1; }
for (int i = 0; i < r.size(); i++)
{
temp = new Rectangle(r.elementAt(i));
int rx = temp.x;
int ry = temp.y;
int rh = temp.height;
int rw = temp.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;}
}
//Increment or decrement the location of the ball based on the X and Y directions.
loc.x += dx;
loc.y += dy;
}
If you want to view the code in its entirety, it’s here: http://ideone.com/R1hpBx
Thanks in advance for all the wonderful help.
I finally found a edge detection system I like…
Basically, the magic happens here…
Now, I only have a single obstacle, but I doubt it would take much effort to get it working with a series of obstacles… 😉