Last active
October 9, 2024 13:10
-
-
Save Daniel-Hug/d7984d82b58d6d2679a087d896ca3d2b to your computer and use it in GitHub Desktop.
JS functions: check if 2 rectangles intersect, are touching, or if one contains the other
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
// Check if rectangle a contains rectangle b | |
// Each object (a and b) should have 2 properties to represent the | |
// top-left corner (x1, y1) and 2 for the bottom-right corner (x2, y2). | |
function contains(a, b) { | |
return !( | |
b.x1 < a.x1 || | |
b.y1 < a.y1 || | |
b.x2 > a.x2 || | |
b.y2 > a.y2 | |
); | |
} | |
// Check if rectangle a overlaps rectangle b | |
// Each object (a and b) should have 2 properties to represent the | |
// top-left corner (x1, y1) and 2 for the bottom-right corner (x2, y2). | |
function overlaps(a, b) { | |
// no horizontal overlap | |
if (a.x1 >= b.x2 || b.x1 >= a.x2) return false; | |
// no vertical overlap | |
if (a.y1 >= b.y2 || b.y1 >= a.y2) return false; | |
return true; | |
} | |
// Check if rectangle a touches rectangle b | |
// Each object (a and b) should have 2 properties to represent the | |
// top-left corner (x1, y1) and 2 for the bottom-right corner (x2, y2). | |
function touches(a, b) { | |
// has horizontal gap | |
if (a.x1 > b.x2 || b.x1 > a.x2) return false; | |
// has vertical gap | |
if (a.y1 > b.y2 || b.y1 > a.y2) return false; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment