0

Give a rect s1 = {x, y, w, h} and another rects s2 = {x, y, w, h} and a vector v = {x, y}. And assuming that s1 has moved according to v, I want to check if it is overlapping.

I have this algorithm:

isOverlapping = not (s1.x + s1.w + v.x < s2.x
or s1.x + v.x > s2.x + s2.w
or s1.y + s1.h + v.y < s2.y
or s1.h + v.y > s2.y + s2.h)

But it doesn't seem to work correctly, but I can't even say what is wrong with it, because I don't understand it at all. And because of its nature I can't even seem to break it apart into smaller pieces.

isOverlapping = not (right_edge_of_s1_plus_move < left_edge_of_s2
or left_edge_of_s1_plus_move > right_edge_of_s2
or top_edge_of_s1_plus_move < bottom_edge_of_s2
or bottom_edge_of_s1_plus_move > top_edge_of_s2)

isOverlapping = not (s1_overlaps_s2_on_left_edge
or s1_overlaps_s2_on_right_edge
or s1_overlaps_s2_on_bottom_edge
or s1_overlaps_s2_on_top_edge)

That implies that they are not not overlapping as soon as s1 overlaps s2 on one edge... What?

The weird thing is, that in my program, it only does not work, when s1 tries to move under s2. Everything else works.

So my question is: What is the correct algorithm for testing if two moving boxes are overlapping each other (AABB) and what kind of algorithm do I have here? I know I got it from somewhere, but I can't find my source anymore. I just added the extra movement vector.

hgiesel
  • 5,430
  • 2
  • 29
  • 56
  • 2
    use this: http://gamedev.stackexchange.com/a/587 – Tamás Zahola Jan 22 '17 at 15:30
  • Okay this works fine, but I'm still interested in why the other algorithm is wrong / what in heavens I calculated there. Because it worked partly. – hgiesel Jan 22 '17 at 15:39
  • btw, if your AABB doesn't change it's size, then you only need to check if the displacement vector's x/y is smaller than the rectangle's width/height. I.e.: `isOverlapping = abs(v.x) < width && abs(v.y) < height` – Tamás Zahola Jan 22 '17 at 15:43
  • Then which rectangle's width? The moving AABB or the stationary AABB? – hgiesel Jan 22 '17 at 16:02
  • Oh, so you have two different rectangles. I thought you have one rectangle, and you want to check whether it overlaps with it's original position after displacing it with a vector. – Tamás Zahola Jan 22 '17 at 16:59
  • 1
    I've used this algorithm successfully several times. It's a bit more efficient than the one given by Tamás Zahola. Your problem as @FrankPuffer said is just a typo. It's easy to tell by this question that you're not writing unit tests. Strongly consider doing so. – Gene Jan 22 '17 at 18:26

1 Answers1

2

The error is caused by a simple typo. The first variable in the last comparison should be s1.y instead of s1.h:

isOverlapping = 
    not (s1.x + s1.w + v.x < s2.x
      or s1.x + v.x > s2.x + s2.w
      or s1.y + s1.h + v.y < s2.y
      or s1.y + v.y > s2.y + s2.h)
Frank Puffer
  • 8,135
  • 2
  • 20
  • 45