Skip to content

Instantly share code, notes, and snippets.

@mattlundstrom
Last active October 24, 2020 21:29
Show Gist options
  • Save mattlundstrom/ecc794df3f4e9f1ddb8015e02cbb47fc to your computer and use it in GitHub Desktop.
Save mattlundstrom/ecc794df3f4e9f1ddb8015e02cbb47fc to your computer and use it in GitHub Desktop.
JS is a rectangle colliding with a circle?
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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment