Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS How to tell if two 2d boxes are touching using their vertex coordinates?

I have a 2d game in which I need to check collisions properly.
For example I need to check if one box touches another, when I have the cordinates of top left vertices of both and their side lengths.

// where side is side length
function touches(x1, y1, size1, x2, y2, size2){
     ...
}

I couldn’t find any questions like this here, is there a way to create a function like this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To check if the two squares either touch or overlap, you can check if both the x and y coordinates are within the same range.

function touches(x1, y1, size1, x2, y2, size2){
    return (x1 >= x2 && x1 <= x2 + size2 || x2 >= x1 && x2 <= x1 + size1)
        && (y1 >= y2 && y1 <= y2 + size2 || y2 >= y1 && y2 <= y1 + size1);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading