Let’s see, some Maths time. Let me see if I can come up with something that’ll work/be intelligent.
- Except for corners, a rectangle is most likely to collide against circle in such a way that a the impacting side forms a line tangent to circle.
1.2) Since many impacts will occur at a line tangent to the circle, we can disregard angle in these cases.
1.3) In these cases, a collision can be detected by just figuring out which edge is closest to the circle, then checking whether the distance from this edge is less-than-or-equal to the circle’s radius. (This can be done by finding the line perpendicular to the line formed by that edge of the rectangle, and then shifting it so that the line passes through the center of the circle.)
- Corners are a special case
2.2) An impact against a corner can just be checked by seeing whether the distance from the center of the circle to the closest corner is less-than-or-equal to the circle’s radius.
So, you’d have four ‘lines’ that would be the lines perpendicular to the edges and then the four corners. So…
Let’s say we have Circle, r=2 at (1,1).
Then we have a rectangle with points (3,3), (4,4), (2,4), (3,5).
Check if the points intersect first. (Can do radiusradius > (cornerX - circleX)^2 + (cornerY - circleY)^2. If any are true, it’s a corner collision.
radiusradius = 22 = 4.
(3,3): 4 > 22 + 22 = false
(4,4): 4 > 33 + 33 = false
(2,4): 4 > 11 + 33 = false
(3,5): 4 > 22 + 4*4 = false
First we find the Parallel and Perpendicular lines for each edge. In this case, we want the ‘range’ of the Perpendicular line. We get that by finding the slope, then solving for B in Y=MX+B.
(3,3) - (4,4): Y = X and Y = -X + [6,8]
(2,4) - (3,5): Y = X - 2 and Y = -X + [6,8]
(4,4) - (2,4): Y = -X + 8 and Y = X + [0,2]
(4,4) - (2,4): Y = -X + 6 and Y = X + [0,2]
So then we take those two lines and plug in the center of the circle, and solve for B. B = 0 and B = 0. If B is between the bounds we found earlier then if there is a collision, it will be against that edge. In this case, we have Y = X + [0,2]. So then we just solve for the intersection of:
Y = X and Y = -X + 8 which is X = - X + 8, which means that X = 4. We plug that into Y = X, and get (4,4).
Y = X and Y = -X + 6 which is X = - X + 6, which means that X = 3. We plug that into Y = X, and get (3,3).
Check the distance of each (Treat it like the point before), which is radius*radius > (cornerX - circleX)^2 + (cornerY - circleY)^2.
We’ve already done this check earlier, since I picked a stupid box. But it should be fairly easy to solve most of these.
A lot of these formulas can be hard coded into objects, so that it shouldn’t be too difficult to write them, and shouldn’t be too costly to figure them out.
And this is probably more math than you needed to know. 