I am having problems figuring out this part of the program:
Write a non-member function, intersection() that takes two Rectangle parameters and returns a Rectangle containing the intersection of the two. Of course, if the two Rectangles don't intersect, it should return the default Rectangle.
So far this is my .cpp code:
Rectangle::Rectangle()
{
p1.x = 0;
p1.y = 0;
p2.x = 0;
p2.y = 0;
}
Rectangle::Rectangle(double x, double y, double width, double height)
{
p1.x = x;
p1.y = y;
p2.x = x + width;
p2.y = y + height;
}
double Rectangle::getArea() const
{
return (p2.x - p1.x) * (p2.y - p1.y);
}
double Rectangle::getWidth() const
{
return (p2.x - p1.x);
}
double Rectangle::getHeight() const
{
return (p2.y - p1.y);
}
double Rectangle::getX() const
{
return p1.x;
}
double Rectangle::getY() const
{
return p1.y;
}
void Rectangle::setLocation(double x, double y)
{
p1.x = x;
p1.y = y;
}
void Rectangle::setSize(double width, double height)
{
p2.x = width;
p2.y = height;
}
Rectangle intersection(const Rectangle& rec1, const Rectangle& rec2)
{
double ix = 0.0;
double iy = 0.0;
double iwidth = 0.0;
double iheight = 0.0;
if(rec1.getX() > rec2.getX() && rec2.getX() > (rec1.getX() + rec1.getWidth())
&& rec1.getY() > rec2.getY() && rec2.getY() > (rec1.getY() + rec1.getHeight()))
{
ix = rec2.getX();
iy = rec2.getY();
iwidth = rec1.getX() + rec1.getWidth();
iheight = rec1.getY() + rec1.getHeight();
}
I didn't write the "else" part because first, this "if statement should check correct for some cases, but doesn't; I am assuming that (0, 0) is in the bottom left corner, because I already try it with (0, 0) being in the top left corner and does not work