Skip to content

Instantly share code, notes, and snippets.

@larsemil
Created March 17, 2021 08:22
Show Gist options
  • Save larsemil/5d838ff113a203f7b0f28ca5d339402b to your computer and use it in GitHub Desktop.
Save larsemil/5d838ff113a203f7b0f28ca5d339402b to your computer and use it in GitHub Desktop.
Javascript rectangle intersect function
/**
* 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 );
}
@larsemil
Copy link
Author

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:

var player = {
    x:10,
    y:100,
    width: 20,
    height: 20
}

var enemy = {
    x:20,
    y:100,
    width: 20,
    height: 20
}

if(intersects(player,enemy)){
    //Det som ska hända
    alert("game over")
}

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