0

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?

Just kesha
  • 43
  • 1
  • 1
  • 7
  • 1
    https://stackoverflow.com/questions/16005136/how-do-i-see-if-two-rectangles-intersect-in-javascript-or-pseudocode – epascarello Dec 14 '21 at 18:12

1 Answers1

1

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);
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80