Search code examples
androidgeometrycollision-detection

Getting the overlapping area of two circles


I'm in a tremendous bind with a last minute request on a consulting project I'm working on.

Essentially here is what I am trying to accomplish:

I have a surfaceview that draws a series of randomly sized circles. Each circle can have a radius from 50-100.

The x,y values are randomly generated along with a random radius

Each circle is created as an object representing that circle (x, y coord's and radius) and it is added to a list.

Once they are all created they are drawn.

The problem is I want to make sure none of these circles overlap.

I'm struggling a bit. This seems like it's shouldn't be all that difficult but it is for me unfortunately.

Here's my code so far (I know it's not close...be kind):

    x = 100 + (int) (Math.random() * (mCanvasWidth - 200));
    y = 100 + (int) (Math.random() * (mCanvasHeight - 200));
    radius = 50 + (int) (Math.random() * 99);
    color[0] = (float) (Math.random() * 360);
    color[1] = 1;
    color[2] = 1;

    String radVal = String.valueOf(radius);

    circle circ = new circle(x, y, radius, Color.HSVToColor(128, color), radVal);

    boolean addit = true;



    for (dot d : Dots) {
        int leftSide = d.get_x() - radius;
        int rightSide = d.get_x() + radius;

        int xBoundary = x + radius;
        int yBoundary = y + radius;

        int exist_xLeft = d.get_x() - d.get_radius();
        int exist_xRight = d.get_x() + d.get_radius();
        int exist_yTop = d.get_y() - d.get_radius();
        int exist_yBottom = d.get_y() + d.get_radius();

        if ((xBoundary > exist_xLeft) && (xBoundary < exist_xRight))
        {
            if (yBoundary > (exist_yTop) && (yBoundary < exist_yBottom)) {
                addit = false;
                break;
            }
        }
    }

    if (addit)
        circles.add(mdot);

    if (circles.size() >= 5)
        running = false;

Then it iterates the circles list and draws them to the canvas.

Any suggestions on where I'm failing in the collision detection?


Solution

  • You can detect if 2 circles are colliding like this:

    Given:

    • centerpoints cx1,cy1 & cx2,cy2

    • and given radii r1 & r2,

    Then you can determine if the 2 circles are colliding:

    areColliding=((cx2-cx1)*(cx2-cx1)+(cy2-cy1)*(cy2-cy1))<((r1+r2)*(r1+r2));