Created
March 17, 2021 08:22
-
-
Save larsemil/5d838ff113a203f7b0f28ca5d339402b to your computer and use it in GitHub Desktop.
Javascript rectangle intersect function
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 two objects intersect | |
* | |
* Objects need to have x,y,width,height properties | |
* | |
* @param {object} obj1 - The first object. | |
* @param {object} obj2 - The second object. | |
* @returns {boolean} true if objects intersect | |
*/ | |
function intersects(obj1, obj2) { | |
//if obj1 misses paramters return false | |
if (!(obj1.hasOwnProperty("x") || obj1.hasOwnProperty("y") || obj1.hasOwnProperty("width") || obj1.hasOwnProperty("height"))) { | |
return false | |
} | |
//if obj1 misses paramters | |
if (!(obj2.hasOwnProperty("x") || obj2.hasOwnProperty("y") || obj2.hasOwnProperty("width") || obj2.hasOwnProperty("height"))) { | |
return false | |
} | |
//check outermost points | |
let obj1LeftOf2 = obj1.x + obj1.width < obj2.x; | |
let obj1RightOf2 = obj1.x > obj2.x + obj2.width; | |
let obj1Above2 = obj1.y > obj2.y + obj2.height; | |
let obj1Below2 = obj1.y + obj1.height < obj2.y; | |
return !( obj1LeftOf2 || obj1RightOf2 || obj1Above2 || obj1Below2 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Den här koden används för att kolla om två javascriptobjekt korsar varandra.
För att det ska fungera så måste båda objekten ha följande properties:
x,y,width,height
.Exempel: