Skip to content

Instantly share code, notes, and snippets.

@vonWolfehaus
Last active October 18, 2021 00:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vonWolfehaus/5023015 to your computer and use it in GitHub Desktop.
Save vonWolfehaus/5023015 to your computer and use it in GitHub Desktop.
Circle to rectangle collision detection
// limits value to the range min..max
function clamp(val, min, max) {
return Math.max(min, Math.min(max, val))
}
// Find the closest point to the circle within the rectangle
// Assumes axis alignment! ie rect must not be rotated
var closestX = clamp(circle.X, rectangle.x, rectangle.x + rectangle.width);
var closestY = clamp(circle.Y, rectangle.y, rectangle.y + rectangle.height);
// Calculate the distance between the circle's center and this closest point
var distanceX = circle.X - closestX;
var distanceY = circle.Y - closestY;
// If the distance is less than the circle's radius, an intersection occurs
var distanceSquared = (distanceX * distanceX) + (distanceY * distanceY);
return distanceSquared < (circle.Radius * circle.Radius);
// expensive alternative:
function intersects(circle, rect) {
circleDistance.x = Math.abs(circle.x - rect.x);
circleDistance.y = Math.abs(circle.y - rect.y);
if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }
if (circleDistance.x <= (rect.width/2)) { return true; }
if (circleDistance.y <= (rect.height/2)) { return true; }
cornerDistanceSq = Math.sqr(circleDistance.x - rect.width/2) +
Math.sqr(circleDistance.y - rect.height/2);
return (cornerDistanceSq <= (Math.sqr(circle.r)));
}
@sophiene1
Copy link

sophiene1 commented Jun 7, 2018

create a variable circleDistance = {};
and you should use circleDistance.x and circleDistance.y or rename circleDistanceX and circleDistanceY
math.sqrt*()
ty bro

@WalrusGumboot
Copy link

Thanks a lot fam, helped me out in a game jam.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment