Suppose i have a rectangle defined by a point (its upper left corner), and a width and height like this (in C++):
class Rectangle
{
public:
Rectangle(float _x, float _y, float _width, float _height);
~Rectangle();
float X, Y, Width, Height;
bool intersects(Rectangle& _rect)
{
return (
(X < _rect.X + _rect.Width)&&
(X + Width > _rect.X)&&
(Y < _rect.Y + _rect.Height)&&
(Y + Height > _rect.Y)
);
}
}
The above intersects
function returns true if the rectangles overlap - if they collide. But what if i want to find out which side of the rectangle the other rectangle collided with? How would i do that (efficiently, but not a priority)?
In case of collision is detected there are 16 different variants
How I got this table? There are 4 different places avaliable for upper-left corner of the red rect. First line is first variant, second line - second variant and so on. Also there are 4 diff. places for down-right corner of the red rect. And I also put each variant in a separate column.
For example, we want to know does the top side of (*this) (let it be red) collide with _rect (let it be blue). It's true for variants 9,10,11,12,14,16. So the case is
(_rect.Y < Y < _rect.Y + _rect.Height) &&
(X < _rect.X || X + Width > _rect.X + _rect.Width)