0

I have code that (correctly) gets the 4 corner's x and y position. I want to know if element A is within the bounds of element B at all (even by 1px). I can't for the life of me figure out the right equation for this.

I have this, but this only checks if the top left of A is inside of B.

xIntersects = a.topLeft.x >= b.topLeft.x && a.topLeft.x <= b.topRight.x;
yIntersects = a.topLeft.y >= b.topLeft.y && a.topLeft.y <= b.bottomLeft.y;

console.log(xIntersects && yIntersects) // true only when topLeft of A is in B

I can write a statement like this for each of the four corners, but that seems really expensive and there's probably a much nicer way of handling this.

My code is in JS, but this answer could really be in any language.

Oscar Godson
  • 31,662
  • 41
  • 121
  • 201
  • 1
    http://stackoverflow.com/questions/2752349/fast-rectangle-to-rectangle-intersection – Cyclonecode Jul 01 '14 at 22:48
  • Sorry if this is a dumb question, but the code you linked to checks if only top, left, bottom, or right intersect. That'd work, but I have x,y coords for each corner, not each side. How would I convert my x,y to sides? – Oscar Godson Jul 01 '14 at 22:54
  • If the orientation of the corners for each rectangle is always the same, you only need 4 checks: two on two diagonals (e.g. top left of inner is lower and to the right of the outer, and bottom right of inner is higher and to the left of the outer). Of course you need to convert "left", "right", "higher", "lower" into your coordinate system and sense. – RobG Jul 01 '14 at 22:55
  • Do you know the width and height of the rectangle? In that case you can easily calculate the sides from your points. – Cyclonecode Jul 01 '14 at 22:57

1 Answers1

0

Ended up using

  function intersects (el1, el2) {
    var a = el1.getCoordinates();
    var b = el2.getCoordinates();
    return   (a.left <= b.right &&
              b.left <= a.right &&
              a.top <= b.bottom &&
              b.top <= a.bottom)
  }

If you use MooTools getCoordinates returns the top, left, bottom, and right. If not you need to figure that out manually.

Oscar Godson
  • 31,662
  • 41
  • 121
  • 201