Detect if circle A is completely inside circle B

The following is a function that determines if two circles intersect. I want to change it to determine only the intersection of the peripherals of the circles. Therefore, if the circle A is completely inside the circle B, a collision does not occur!

How?

private bool IsCircleCollision( int x1, int y1, int radius1, int x2, int y2, int radius2) { int dx = x2 - x1; int dy = y2 - y1; int distance = (dx * dx) + (dy * dy); int radii = radius1 + radius2; if (distance < radii * radii) { return true; } else { return false; } } 
+4
source share
4 answers

You handle this by calculating the distance between the two centers, D say. There is an intersection if

 abs(R1-R2) < D < R1+R2 

where R1 and R2 are the radii of two circles.

The first abs(R1-R2) < D test abs(R1-R2) < D handles the case when one center of the circle is inside another. And the second test D < R1+R2 handles the case when no circle contains another center.

So, adapting our code, we have:

 private bool IsCircleCollision( int x1, int y1, int radius1, int x2, int y2, int radius2) { int dx = x2 - x1; int dy = y2 - y1; double D = Math.Sqrt(dx*dx + dy*dy); return Math.Abs(radius1-radius2)<D && D<radius1+radius2; } 

If performance is important here, you can do without calling Math.Sqrt as follows:

 private bool IsCircleCollision( int x1, int y1, int radius1, int x2, int y2, int radius2) { int dx = x2 - x1; int dy = y2 - y1; int Dsqr = dx*dx + dy*dy; int rdiff = Math.Abs(radius1-radius2); int rsum = radius1+radius2 return rdiff*rdiff<Dsqr && D<rsum*rsum; } 
+7
source

They will intersect along the perimeter if and only if the distance between the two centers is less than or equal to the sum of the two radii, but greater than or equal to their absolute difference. With this fact, it should not be difficult to rewrite the function.

+2
source

You can add a check to see if distance + radius1 radius2 or distance + radius2 less than radius1 , but then you need distance be the actual distance, not its square.

0
source
 else if (Math.Sqrt(dx * dx + dy * dy) < Math.Abs(radius1 - radius2)) 
0
source

Source: https://habr.com/ru/post/1432116/


All Articles