Last active
November 7, 2024 19:26
-
-
Save vonWolfehaus/5023015 to your computer and use it in GitHub Desktop.
Circle to rectangle collision detection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code! Although, the corner detection was off. Instead of testing if the cornerDistance was less than or equal to the square root of the radius, I tested for half of the radius of the circle and that fixed it!