mtijn
mtijn

Reputation: 3678

get vector between 2 rectangles

suppose I have 2 rectangles as follows:

  1. one encloses the other
  2. they share at least 2 sides (3 or all 4 also possible)

how do I get the vector that describes the displacement required for the inner rectangle to move upto the non-shared side(s)?

Upvotes: 2

Views: 638

Answers (2)

Arie
Arie

Reputation: 5373

It's more like a math than programming question :)

Lets assume you have two rectangles: A (inside) and B (outside). They have 4 corners:

Point [] GetCorners (Rectangle rect)
{
   Point [] corners = new Point[4];

   Point corners[0] = new Point(rect.X, rect.Y);
   Point corners[1] = new Point(rect.X + rect.Width, rect.Y);
   Point corners[2] = new Point(rect.X, rect.Y + rect.Height);
   Point corners[3] = new Point(rect.X + rect.Width + rect.Width, rect.Y);

   return corners;
}

First find the first shared corner:

Point [] cornersListA = GetCorners(A);
Point [] cornersListB = GetCorners(B);

int sharedCornerIndex = 0;
for (int i=0; i<4; i++)
{
  if(cornersListA[i].X==cornersListB[i].X && cornersListA[i].Y==cornersListB[i].Y)
  {
     sharedCornerIndex = i;
     break;
  }
}

Then find the corner oposite of it:

int oppositeCornerIndex = 0;
if(sharedCornerIndex ==0) oppositeCornerIndex = 3;
if(sharedCornerIndex ==3) oppositeCornerIndex = 0;
if(sharedCornerIndex ==1) oppositeCornerIndex = 2;
if(sharedCornerIndex ==2) oppositeCornerIndex = 1;

Finally, get vector (I didn't check this part of the code, but it should work):

Vector v = new Vector();
v.X = cornersListB[oppositeCornerIndex].X - cornersListA[oppositeCornerIndex].X;
v.Y = cornersListB[oppositeCornerIndex].Y - cornersListA[oppositeCornerIndex].Y;

Upvotes: 2

Piotr Auguscik
Piotr Auguscik

Reputation: 3681

If i understood you correctly, then you you should follow those steps:

  1. Find corner that both sides are shared.
  2. Get oposit corner from inner and outer rectangles.
  3. vector = outerRecCorner - innerRecCorner

Upvotes: 3

Related Questions