Created
June 17, 2021 21:43
-
-
Save dalequark/85213496b784a1c0cabeb988284cb509 to your computer and use it in GitHub Desktop.
bbox distance
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
class BBox { | |
constructor(bbox) { | |
let x = bbox[0]; | |
let y = bbox[1]; | |
this.width = bbox[2]; | |
this.height = bbox[3]; | |
this.midX = x + this.width / 2; | |
this.midY = y + this.height / 2; | |
} | |
distance(bbox) { | |
let xDiff = Math.abs(this.midX - bbox.midX) - this.width / 2 - bbox.width / 2; | |
let yDiff = Math.abs(this.midY - bbox.midY) - this.height / 2 - bbox.height / 2; | |
// If xDiff < 0, the boxes intersect in the x plane. Thus the distance is just the | |
// y height, or 0 if the boxes intersect in the y plane, too. | |
if(xDiff < 0) { | |
return Math.max(yDiff, 0); | |
} | |
// In this case, boxes intersect in y plane but not x plane. | |
if(yDiff < 0) { | |
return xDiff; | |
} | |
// BBoxes intersect in neither plane. Return the Euclidean distance between | |
// the closest corners. | |
return Math.sqrt(xDiff**2 + yDiff**2); | |
} | |
} | |
function checkIfNear(item1, item2, distance=0) { | |
const BOUNDING_BOX_1 = new BBox(item1.bbox); | |
const BOUNDING_BOX_2 = new BBox(item2.bbox); | |
return BOUNDING_BOX_1.distance(BOUNDING_BOX_2) <= distance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment