-1

Could somebody explain to me how this works or link to a site/video where this gets explained.

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // collision detected!
}
Bharata
  • 13,509
  • 6
  • 36
  • 50
MetaByte
  • 5
  • 1
  • Its just like when you create an empty graph in math. When you draw the bottom line you draw `x`. Where the pencil starts is `x = 0`, where the pencil ends is `x+width` = how many centimeters the line is, if you drew a vertical line on the start and the end, then you would know when the left side and the right side were hit. The same thing applies for `y`, except the top and bottom would have bounds now – Pavlo Jan 14 '18 at 21:16

2 Answers2

0

your asking about box to box collision, check my answer out here, its for android but the code would be the same. it also has the extra axis for 3d collision but is the same for 2d just remove the z-axis

Answer

Rob85
  • 1,719
  • 1
  • 23
  • 46
0

First, imagine a grid. The lines that run up and down give an x-coordinate, the ones running left and right give a y-coordinate.

A rectangle on that grid (assuming it lines up with the grid lines) will have 4 coordinate pairs: top-left, bottom-left, top-right, bottom right. The rect.x and rect.y seem to be the bottom-left coordinates. The code then checks to see if there is any overlap between the rectangles.

This particular method is called bounding box collision detection, and the MDN site in the link seems to be the source of the code.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83