I came across this topic on Stackoverflow about collision detection between a circle and a rectangle.
The original post can be found here @markE: Detecting collision of rectangle with circle
var circle={x:100,y:290,r:10};
var rect={x:100,y:100,w:40,h:100};
// return true if the rectangle and circle are colliding
function RectCircleColliding(circle,rect){
var distX = Math.abs(circle.x - rect.x-rect.w/2);
var distY = Math.abs(circle.y - rect.y-rect.h/2);
if (distX > (rect.w/2 + circle.r)) { return false; }
if (distY > (rect.h/2 + circle.r)) { return false; }
if (distX <= (rect.w/2)) { return true; }
if (distY <= (rect.h/2)) { return true; }
var dx=distX-rect.w/2;
var dy=distY-rect.h/2;
return (dx*dx+dy*dy<=(circle.r*circle.r));
}
Can someone please explain the last bit of code to me?
var dx=distX-rect.w/2;
var dy=distY-rect.h/2;
return (dx*dx+dy*dy<=(circle.r*circle.r));
I really don't understand the math behind it.
Maybe someone can post a photo that might help me visualize it? I have attached a photo that I drew while trying to figure it out.
Thank you
