Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find collision center of two rectangles? Rects can be rotated

I've just implemented collision detection using SAT and this article as reference to my implementation. The detection is working as expected but I need to know where both rectangles are colliding.

I need the center of the intersectionMore examples

I need to find the center of the intersection, the black point on the image above (but I don't have the intersection area neither). I've found some articles about this but they all involve avoiding the overlap or some kind of velocity, I don't need this.

The information I've about the rectangles are the four points that represents them, the upper right, upper left, lower right and lower left coordinates. I'm trying to find an algorithm that can give me the intersection of these points.

I just need to put a image on top of it. Like two cars crashed so I put an image on top of the collision center. Any ideas?

like image 296
Felipe Cypriano Avatar asked Oct 02 '12 21:10

Felipe Cypriano


1 Answers

There is another way of doing this: finding the center of mass of the collision area by sampling points.

Create the following function:

bool IsPointInsideRectangle(Rectangle r, Point p);

Define a search rectangle as:

TopLeft = (MIN(x), MAX(y))
TopRight = (MAX(x), MAX(y))
LowerLeft = (MIN(x), MIN(y))
LowerRight = (MAX(x), MIN(y))

Where x and y are the coordinates of both rectangles.

You will now define a step for dividing the search area like a mesh. I suggest you use AVG(W,H)/2 where W and H are the width and height of the search area.

Then, you iterate on the mesh points finding for each one if it is inside the collition area:

IsPointInsideRectangle(rectangle1, point) AND IsPointInsideRectangle(rectangle2, point) 

Define:

Xi : the ith partition of the mesh in X axis.
CXi: the count of mesh points that are inside the collision area for Xi.

Then:

enter image description here

And you can do the same thing with Y off course. Here is an ilustrative example of this approach:

enter image description here

like image 152
daniloquio Avatar answered Oct 21 '22 10:10

daniloquio