Rectagle Circle Collision, something strange in this.
Posted: Thu Mar 23, 2023 11:02 am
I googled Circle-Rectangle Collision, and they seem to suggst following:
what seems strange to me is for example this part:
for it don't seem to work.
Lets take an example of Rectangle starting at X=1 and Circle at X=200
Rectangles width is 100 and Circles Radius is 100 as well.
Therefore using this calculation, Xdistance is 199.
Using
(rw / 2 + cr) =
100/2 + 100 =
50 + 100 =
150
In reality Rectangles Width being 100, would make it reach to X spot 101.
Circle on the other hand from X=200 with 100 Radius, would reach X spot 100.
Meaning there is overlap (=collision) in spot X100 and X101 between those two.
Yet these Circle-Rectangle collisions are giving FALSE as the result in this kind of case.
What am I not getting here, or are they all really wrong about their Circle-Rectangle Collision detection code?
Code: Select all
local math_abs = math.abs
function circlerect_colliding(cx, cy, cr, rx, ry, rw, rh)
circleDistance_x = math_abs(cx - rx)
circleDistance_y = math_abs(cy - ry)
if circleDistance_x > (rw / 2 + cr) then
return false
end
if circleDistance_y > (rh / 2 + cr) then
return false
end
if circleDistance_x <= (rw / 2) then
return true
end
if circleDistance_y <= (rh / 2) then
return true
end
cornerDistance_sq = (circleDistance_x - rw / 2) ^ 2 + (circleDistance_y - rh / 2) ^ 2
return (cornerDistance_sq <= (cr ^ 2))
endCode: Select all
if circleDistance_x > (rw / 2 + cr) then
return false
endLets take an example of Rectangle starting at X=1 and Circle at X=200
Rectangles width is 100 and Circles Radius is 100 as well.
Therefore using this calculation, Xdistance is 199.
Using
(rw / 2 + cr) =
100/2 + 100 =
50 + 100 =
150
In reality Rectangles Width being 100, would make it reach to X spot 101.
Circle on the other hand from X=200 with 100 Radius, would reach X spot 100.
Meaning there is overlap (=collision) in spot X100 and X101 between those two.
Yet these Circle-Rectangle collisions are giving FALSE as the result in this kind of case.
What am I not getting here, or are they all really wrong about their Circle-Rectangle Collision detection code?