Reputation: 35
As a online graphical I used: https://www.khanacademy.org/computer-programming/spin-off-of-rectx-y-width-height-radius/4975791745220608
The rectangle coordinates:
rectangle 1: x: 180 y: 30
rectangle 2: x: 160 y: 30
What I noticed is that the render begins from a point and is increased on X axis by width and Y axis by height. So i deduced the following things: x1 and y1 are equal to rectangle coordinates (x1 and y1 being the top left corner) and x2, y2 are the bottom right corner/coordinates which are equal to the sum of square coordinates or in other words x1 and y1 and the width & height of the square.
That's the code i made:
#include <stdio.h>
#include <iostream>
struct A
{
int x1, x2;
int y1, y2;
};
struct B
{
int x1, x2;
int y1, y2;
};
bool doOverlap(A a, B b)
{
if (a.x1 < b.x2 && a.x2 > b.x1 &&
a.y1 > b.y2 && a.y2 < b.y1)
return true;
return false;
}
int main()
{
/*
Rectangle 1 coords: X: 180 Y: 30
Rectangle 2 coords: X: 160 Y: 30
*/
A a;
B b;
/*
The render begins from top left corner (that's our center and
from here begins the render with +width on x and +heigth on y
(correct me in case i'm wrong but that's what i noticed: https://imgur.com/a/nZKBB0m
(as can you see in that photo, the white rectangle has l1: (x,y): 0 0)
rectangles are 40x40
*/
a.x1 = 180;
a.y1 = 30;
a.x2 = a.x1 + 40;
a.y2 = a.y1 + 40;
b.x1 = 160;
b.y1 = 30;
b.x2 = b.x1 + 40;
b.y2 = b.y1 + 40;
if (doOverlap(a, b))
{
std::cout << "y";
}
else
std::cout << "n";
return 0;
}
The problem is it always return false (checked a lot of codes but no one of them seems like are working) So,what do i do wrong?
Upvotes: 0
Views: 103
Reputation: 119
You're only checking if a is above above b, and then checking if a is left of b. You need to check if the x intervals of a and b overlap, and then check if the y intervals overlap. Here is a way of doing that:
bool doOverlap(A a, B b)
{
if (a.x1 > b.x2 || b.x1 > a.x2)
return false;
if (a.y1 > b.y2 || b.y1 > a.y2)
return false;
return true;
}
The first if checks if the x intervals of a and b overlap, and returns false if they don't. The second does the same for the y intervals. If both the x and y intervals overlap, the rectangles overlap
Upvotes: 2