4

I am trying to implement the following. I have two bounds A and B, I want to transform box B so that the intersection between A and B no longer exists. I'm not sure how to calculate the shift, i want to maintain the direction, i.e the red line.

Bounding Boxes

Haven't written much code, pretty stuck with the math.

var a = new Rectangle(40, 40, 20, 20);
var b = new Rectangle(25, 30, 20, 20);
Rohan West
  • 9,262
  • 3
  • 37
  • 64
  • Just checking: the constructor is (left, bottom, length, height) ? – Jodaka Jul 26 '11 at 04:56
  • the Rectangle constructor is (x, y, width, height) – Rohan West Jul 26 '11 at 04:58
  • And that's the (x,y) of which corner? The bottom left? – Jodaka Jul 26 '11 at 05:01
  • This sounds a bit like minimum translation distance (MTD) collision handling. You should give it a Google. It isn't quite the same - MTD pushes out along only one axis, whereas you want both - but it should give you some hints. – Owen Jul 26 '11 at 05:07
  • I think this one is a special (easier) case of the methods used here: http://stackoverflow.com/questions/3265986/an-algorithm-to-space-out-overlapping-rectangles/3279877#3279877 – Dr. belisarius Jul 26 '11 at 05:27

1 Answers1

1

So for the case you've provided, the shift in b.x (dx) can be calculated as a.x - b.length - b.x. The shift in b.y (dy) can then be calculated in terms of keeping slope constant. So solve for dy in dx/dy = (a.x - b.x)/(a.y - b.y), and that gets you the change in y as well.

However, this is specific to the case you described. Among other things, you need to think about what happens if A and B are flipped, what happens if A.x = B.x, what happens if A.y = B.y, and what happens if the difference in x is smaller than the difference in y. Drawing pictures will probably help immensely, on chart paper if you have it, on blank computer paper if you don't. Hope this is a good start.

Jodaka
  • 1,237
  • 8
  • 16
  • Thanks for you answer, in my example the difference in x is smaller than the difference in y. In your calculation do they have to bee the same? – Rohan West Jul 26 '11 at 21:31
  • It depends on whether or not you want the final products bordering or not. If they just have to be separate, it doesn't matter. If they need to still touch, and the change in x is smaller than the change in y, switch all the x's and y's in the formulas (i.e., find dy first off of a.y, b.height, and b.y, then find dx). If you look at the example you drew, if you found y first by shifting up until the boxes no longer overlapped, then shifted left to keep the angle, your boxes would no longer touch. – Jodaka Jul 26 '11 at 22:00