Algorithm to find all line segment intersections given n lines - algorithm

I'm looking for a algorithm to find all the intersection points given n line segments.
Below is the pseudo code from http://jeffe.cs.illinois.edu/teaching/373/notes/x06-sweepline.pdf
The input S[1 .. n] is an array of line
segments.
label[i] is the label of the ith leftmost endpoint.
sort the endpoints of S from left to right
create an empty label sequence
for i ← 1 to 2n
line ← label[i]
if isLeftEndPoint[i]
Insert(line)
if Intersect(S[line], S[Successor(line)])
return TRUE
if Intersect(S[line], S[Predecessor(line)])
return TRUE
else
if Intersect(S[Successor(line)], S[Predecessor(line)])
return TRUE
Delete(label[i])
return FALSE
Apply the algorithm to the line set below, only one intersection point is checked. What should I do to know the existence of the other 2 intersection points?
line[1] enters
line[2] enters, intersection between line[1] and line[2] is checked.
line[3] enters, intersection between line[2] and line[3] is checked.
line[4] enters, intersection between line[4] and line[1] is checked. Intersection A is found.
line[4] leaves, nothing is checked.
line[1] leaves, nothing is checked.
line[2] leaves, nothing is checked.
line[3] leaves, nothing is checked.

Standard line equation
Ax+By=C
The slope(m) of a line defined by the standard line of equation is
m = -(A/B)
Point-slope line equation
y-y1=m(x-x1)
Substituting m = (-A/B) in the point-slope line equation
y2-y1 = (A/-B)*(x2-x1)
(y2-y1)/(x2-x1) = A/-B
thus:
A = y2-y1
B = x1-x2
C = Ax+By
x = (C-By)/A
y = (C-Ax)/B
Given two lines with equation
A1x1+B1y1=C1 and A2x2+B2y2=C2.
Then the point of intersection between the lines is specified
by the points that make A1x+B1y-C1 = A2x+B2y-C2
A1x+B1y=C1
A2x+B2y=C2
A1B2x+B1B2y=B2C1 (multiply the first equation by B2)
A1B2x+B1B2y-B2C1=0
A2B1x+B1B2y=B1C2 (multiply the second equation by B1)
A2B1x+B1B2y-B1C2=0
Equating the two equations
A1B2x+B1B2y-B2C1=A2B1x+B1B2y-B1C2
A1B2x+B1B2y-B2C1-A2B1x-B1B2y+B1C2=0
A1B2x-B2C1-A2B1x+B1C2=0
A1B2x-A2B1x=B2C1-B1C2
x(A1B2-A2B1)=B2C1-B1C2
x = (B2C1-B1C2)/A1B2-A2B1
A1x+B1y=C1
A2x+B2y=C2
A1A2x+A2B1y=A2C1 (multiply the first equation by A2)
A1A2x+A2B1y-A2C1=0
A1A2x+A1B2y=A1C2 (multiply the second equation by A1)
A1A2x+A1B2y-A1C2=0
Equating the two equations
A1A2x+A2B1y-A2C1=A1A2x+A1B2y-A1C2
A1A2x+A2B1y-A2C1-A1A2x-A1B2y+A1C2=0
A1C2-A2C2=A1B2y-A2B1y
A1B2y-A2B1y=A1C2-A2C2
y(A1B2-A2B1)=A1C2-A2C1
y(A1B2-A2B1)=A1C2-A2C1
y = (A1C2-A2C1)/(A1B1-A2B1)
the denominator in y and in x are the same so
denominator = A1B1-A2B1
thus:
x = (B2C1-B1C2)/denominator
y = (A1C2-A2C1)/denominator
These are the x and y coordinates of the intersection of two lines with points (x1, y1), (x2, y2) and (x3, y3), (x4, y4)
Now for a line segment it's the same but we need to check that the x or y coordinate is in both segments. That means between the x coordinate of both segments with lesser value and the x coordinate of both segments with greater value
This is a C++ program that returns true if the segments intersect and returns false if they don't. If the segments intersect it stores the point of intersection in a variable i.
struct Point
{
float x, y;
};
//p1 and p2 are the points of the first segment
//p3 and p4 are the points of the second segment
bool intersection(Point p1, Point p2, Point p3, Point p4, Point &i)
{
float max1; //x-coordinate with greater value in segment 1
float min1; //x-coordinate with lesse value in segment 1
float max2; //x-coordinate with greater value in segment 2
float min2; //x-coordinate with lesser value in segment 2
float A1 = p2.y - p1.y;
float B1 = p1.x - p2.x;
float C1 = A1 * p1.x + B1 * p1.y;
float A2 = p4.y - p3.y;
float B2 = p3.x - p4.x;
float C2 = A2 * p3.x + B2 * p3.y;
float denom = A1 * B2 - A2 * B1;
if (denom == 0.0) //When denom == 0, is because the lines are parallel
return false; //Parallel lines do not intersect
i.x = (C1 * B2 - C2 * B1) / denom;
i.y = (A1 * C2 - A2 * C1) / denom;
if (p1.x > p2.x)
{
max1 = p1.x;
min1 = p2.x;
}
else
{
max1 = p2.x;
min1 = p1.x;
}
if (p3.x > p4.x)
{
max2 = p3.x;
min2 = p4.x;
}
else
{
max2 = p4.x;
min2 = p3.x;
}
//check if x coordinate is in both segments
if (i.x >= min1 && i.x <= max1 &&
i.x >= min2 && i.x <= max2)
return true;
return false; //Do no intersect, intersection of the lines is not between the segments
}
Now you just need to compare on a loop all the segments and store the intersection point on array.

Related

Linear regression error - line slope wrong

Consider this function:
double calculate_geoHeading(double [] x, double [] y) {
/+ +++++++++
++ This function will return the heading of the best fit line
++
+/
double r;
real xMean = mean(x);
real yMean = mean(y);
real denom = 0;
real numer = 0;
//double cookDistance NOIMPL
for( int i = 0; i < x.length; i++) {
numer += (x[i] - xMean) * (y[i] - yMean);
denom += (x[i] - xMean) * (x[i] - xMean);
}
real b1 = numer / denom ;
real b0 = yMean - (b1 *xMean);
real y0 = b0 + b1 * x[0];
real x0 = x[0];
real yn = b0 + b1 * x[$-1];
real xn = x[$-1];
r = atan2((yn-y0), (xn-x0));
foreach(XX; x) {
auto YY = b0 + b1 * XX;
print_highPrecision_geoArray([YY, XX]);
}
return r;
}
It is written in D. Th array x is a double array of Longitudes, and y is for Latitude. I compute the linear regression through these points, and then compute the slope of this line. This slope is the heading of the path described by these points.
This normally Works,
For this input :
x = [9.87837003485911,9.87836998511341,9.87836993536771,9.878369885622,9.87836966666667,9.87836975210867,9.87836983755067,9.87836992299267,9.87837000843468,9.87837009387668]
y =
[49.0199479977727,49.0199513307348,49.0199546636969,49.0199579966591,49.0199726666667,49.0199759989048,49.0199793311429,49.019982663381,49.0199859956191,49.0199893278572]
I am having this output :
The Red markers show you the first half of the input array, and the second half of the input array is given by the pink ones.
Then, I also have the output of the interpolated y or Latitude values. These values are held in function by the variable YY. The corresponding x or Longitude values are also present.
These interpolated points are also plotted . Half of them are in green - which has the same x values red part of the input. The rest are cyan, which corresponds to the pink part.
The input is a monotonically increasing function, whereas the interpolated output is monotonically decreasing.
Question : What is my error?
My attempt at solution : I have tried with 80 000 other randomly generated Lat / Lon pairs : it works everywhere in those pairs.
So, I am stuck.
The print_highPrecision_geoArray is properly defined, so is the mean function.
I do not want to blame this on a floating point error.
I need an algorithm, that applies the linear regression properly.
Please help.

Quadratic Equation From Points

I need to implement a function that finds the trajectory of a projectile and I have three points - origin, destination and the point of maximum height.
I need to find the correct quadratic function that includes these points.
I'm having a hard time figuring out what to do. Where should I start?
Assume you have your origin and destination on the y-axis,namely x1 and x2. If not you can shift them later.
a*x*x + b*x + c = 0//equation
x1*x2=(c/a);
c = (x1*x2)*a;
x1+x2=(-b/a);
b = (x1+x2)/(-a);
a*((x1+x2)/2)^2 + b*((x1+x2)/2) + c = h//max height
let X=(x1+x2)/2;
a*X*X + ((2*X)/(-a))*X + (x1*x2)*a - h = 0;
Now you can iterate through a=0 until the above equation is true as you have all the values X ,x1 , x2 and h.
double eqn = (-h),a=0;//a=0.Assuming you have declared x1,x2 and X already
while(eqn!=0)
{
a++;
eqn = a*X*X + ((2*X)/(-a))*X + (x1*x2)*a - h;
}
b = (x1+x2)/(-a);
c = (x1*x2)*a;
Thus you got all your coeffecients.

How to compute the intersection between a quadratic bezier curve and a horizontal line?

What I am trying to do get the X coordinates at which a certain bezier curve crosses a horizontal line (a y coordinate). For the moment, I have this code:
function self.getX(y)
if y > maxY or y < minY then
return
end
local a = y1 - y
if a == 0 then
return
end
local b = 2*(y2 - y1)
local c = (y3 - 2*y2 + y1)
local discriminant = (b^2 - 4*a*c )
if discriminant < 0 then
return
else
local aByTwo = 2*a
if discriminant == 0 then
local index1 = -b/aByTwo
if 0 < index1 and index1 < 1 then
return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3
end
else
local theSQRT = math.sqrt(discriminant)
local index1, index2 = (-b -theSQRT)/aByTwo, (-b +theSQRT)/aByTwo
if 0 < index1 and index1 < 1 then
if 0 < index2 and index2 < 1 then
return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3, (1-index2)^2*x1+2*(1-index2)*index2*x2+index2^2*x3
else
return (1-index1)^2*x1+2*(1-index1)*index1*x2+index1^2*x3
end
elseif 0 < index2 and index2 < 1 then
return (1-index2)^2*x1+2*(1-index2)*index2*x2+index2^2*x3
end
end
end
end
A few specifications:
This is Lua code.
local means the variable is local to the chunk of code, so it does not affect the code's functionality.
y1, y2, and y3 are the y coordinate of the 3 points. The same applies to x1, x2, x3.
y is the y coordinate of the horizontal line I am computing.
maxY is the biggest of the 3 y's.
minY is the smallest.
For the moment this code gives me this:
There are 8 bezier curves
The green ones are generated using the normal method: (1-t)^2*x1+2*(1-t)*t*x2+t^2*x3
The red dots are the control points.
The white lines are what is generated using the method described with the code above.
The straight lines are lines, ignore them.
There should be 8 curves, but only 4 are rendered.
Thanks in advance,
Creator!
The Bézier curve has
y(t)=(1-t)^2*y1+2(1-t)*t*y2+t^2*y
which expands to
(y1-2*y2+y3)*t^2+2(y2-y1)*t+y1
You have swapped a and c in the quadratic equation a*t^2+b*t+c=0 required for solving y(t)=y.

Trilateration and locating the point (x,y,z)

I want to find the coordinate of an unknown node which lie somewhere in the space which has its reference distance away from 3 or more nodes which all of them have known coordinate.
This problem is exactly like Trilateration as described here Trilateration.
However, I don't understand the part about "Preliminary and final computations" (refer to the wikipedia site). I don't get where I could find P1, P2 and P3 just so I can put to those equation?
Thanks
Trilateration is the process of finding the center of the area of intersection of three spheres. The center point and radius of each of the three spheres must be known.
Let's consider your three example centerpoints P1 [-1,1], P2 [1,1], and P3 [-1,-1]. The first requirement is that P1' be at the origin, so let us adjust the points accordingly by adding an offset vector V [1,-1] to all three:
P1' = P1 + V = [0, 0]
P2' = P2 + V = [2, 0]
P3' = P3 + V = [0,-2]
Note: Adjusted points are denoted by the ' (prime) annotation.
P2' must also lie on the x-axis. In this case it already does, so no adjustment is necessary.
We will assume the radius of each sphere to be 2.
Now we have 3 equations (given) and 3 unknowns (X, Y, Z of center-of-intersection point).
Solve for P4'x:
x = (r1^2 - r2^2 + d^2) / 2d //(d,0) are coords of P2'
x = (2^2 - 2^2 + 2^2) / 2*2
x = 1
Solve for P4'y:
y = (r1^2 - r3^2 + i^2 + j^2) / 2j - (i/j)x //(i,j) are coords of P3'
y = (2^2 - 2^2 + 0 + -2^2) / 2*-2 - 0
y = -1
Ignore z for 2D problems.
P4' = [1,-1]
Now we translate back to original coordinate space by subtracting the offset vector V:
P4 = P4' - V = [0,0]
The solution point, P4, lies at the origin as expected.
The second half of the article is describing a method of representing a set of points where P1 is not at the origin or P2 is not on the x-axis such that they fit those constraints. I prefer to think of it instead as a translation, but both methods will result in the same solution.
Edit: Rotating P2' to the x-axis
If P2' does not lie on the x-axis after translating P1 to the origin, we must perform a rotation on the view.
First, let's create some new vectors to use as an example:
P1 = [2,3]
P2 = [3,4]
P3 = [5,2]
Remember, we must first translate P1 to the origin. As always, the offset vector, V, is -P1. In this case, V = [-2,-3]
P1' = P1 + V = [2,3] + [-2,-3] = [0, 0]
P2' = P2 + V = [3,4] + [-2,-3] = [1, 1]
P3' = P3 + V = [5,2] + [-2,-3] = [3,-1]
To determine the angle of rotation, we must find the angle between P2' and [1,0] (the x-axis).
We can use the dot product equality:
A dot B = ||A|| ||B|| cos(theta)
When B is [1,0], this can be simplified: A dot B is always just the X component of A, and ||B|| (the magnitude of B) is always a multiplication by 1, and can therefore be ignored.
We now have Ax = ||A|| cos(theta), which we can rearrange to our final equation:
theta = acos(Ax / ||A||)
or in our case:
theta = acos(P2'x / ||P2'||)
We calculate the magnitude of P2' using ||A|| = sqrt(Ax + Ay + Az)
||P2'|| = sqrt(1 + 1 + 0) = sqrt(2)
Plugging that in we can solve for theta
theta = acos(1 / sqrt(2)) = 45 degrees
Now let's use the rotation matrix to rotate the scene by -45 degrees.
Since P2'y is positive, and the rotation matrix rotates counter-clockwise, we'll use a negative rotation to align P2 to the x-axis (if P2'y is negative, don't negate theta).
R(theta) = [cos(theta) -sin(theta)]
[sin(theta) cos(theta)]
R(-45) = [cos(-45) -sin(-45)]
[sin(-45) cos(-45)]
We'll use double prime notation, '', to denote vectors which have been both translated and rotated.
P1'' = [0,0] (no need to calculate this one)
P2'' = [1 cos(-45) - 1 sin(-45)] = [sqrt(2)] = [1.414]
[1 sin(-45) + 1 cos(-45)] = [0] = [0]
P3'' = [3 cos(-45) - (-1) sin(-45)] = [sqrt(2)] = [ 1.414]
[3 sin(-45) + (-1) cos(-45)] = [-2*sqrt(2)] = [-2.828]
Now you can use P1'', P2'', and P3'' to solve for P4''. Apply the reverse rotation to P4'' to get P4', then the reverse translation to get P4, your center point.
To undo the rotation, multiply P4'' by R(-theta), in this case R(45). To undo the translation, subtract the offset vector V, which is the same as adding P1 (assuming you used -P1 as your V originally).
This is the algorithm I use in a 3D printer firmware. It avoids rotating the coordinate system, but it may not be the best.
There are 2 solutions to the trilateration problem. To get the second one, replace "- sqrtf" by "+ sqrtf" in the quadratic equation solution.
Obviously you can use doubles instead of floats if you have enough processor power and memory.
// Primary parameters
float anchorA[3], anchorB[3], anchorC[3]; // XYZ coordinates of the anchors
// Derived parameters
float Da2, Db2, Dc2;
float Xab, Xbc, Xca;
float Yab, Ybc, Yca;
float Zab, Zbc, Zca;
float P, Q, R, P2, U, A;
...
inline float fsquare(float f) { return f * f; }
...
// Precompute the derived parameters - they don't change unless the anchor positions change.
Da2 = fsquare(anchorA[0]) + fsquare(anchorA[1]) + fsquare(anchorA[2]);
Db2 = fsquare(anchorB[0]) + fsquare(anchorB[1]) + fsquare(anchorB[2]);
Dc2 = fsquare(anchorC[0]) + fsquare(anchorC[1]) + fsquare(anchorC[2]);
Xab = anchorA[0] - anchorB[0];
Xbc = anchorB[0] - anchorC[0];
Xca = anchorC[0] - anchorA[0];
Yab = anchorA[1] - anchorB[1];
Ybc = anchorB[1] - anchorC[1];
Yca = anchorC[1] - anchorA[1];
Zab = anchorB[2] - anchorC[2];
Zbc = anchorB[2] - anchorC[2];
Zca = anchorC[2] - anchorA[2];
P = ( anchorB[0] * Yca
- anchorA[0] * anchorC[1]
+ anchorA[1] * anchorC[0]
- anchorB[1] * Xca
) * 2;
P2 = fsquare(P);
Q = ( anchorB[1] * Zca
- anchorA[1] * anchorC[2]
+ anchorA[2] * anchorC[1]
- anchorB[2] * Yca
) * 2;
R = - ( anchorB[0] * Zca
+ anchorA[0] * anchorC[2]
+ anchorA[2] * anchorC[0]
- anchorB[2] * Xca
) * 2;
U = (anchorA[2] * P2) + (anchorA[0] * Q * P) + (anchorA[1] * R * P);
A = (P2 + fsquare(Q) + fsquare(R)) * 2;
...
// Calculate Cartesian coordinates given the distances to the anchors (La, Lb and Lc)
// First calculate PQRST such that x = (Qz + S)/P, y = (Rz + T)/P.
// P, Q and R depend only on the anchor positions, so they are pre-computed
const float S = - Yab * (fsquare(Lc) - Dc2)
- Yca * (fsquare(Lb) - Db2)
- Ybc * (fsquare(La) - Da2);
const float T = - Xab * (fsquare(Lc) - Dc2)
+ Xca * (fsquare(Lb) - Db2)
+ Xbc * (fsquare(La) - Da2);
// Calculate quadratic equation coefficients
const float halfB = (S * Q) - (R * T) - U;
const float C = fsquare(S) + fsquare(T) + (anchorA[1] * T - anchorA[0] * S) * P * 2 + (Da2 - fsquare(La)) * P2;
// Solve the quadratic equation for z
float z = (- halfB - sqrtf(fsquare(halfB) - A * C))/A;
// Substitute back for X and Y
float x = (Q * z + S)/P;
float y = (R * z + T)/P;
Here are the Wikipedia calculations, presented in an OpenSCAD script, which I think helps to understand the problem in a visual wayand provides an easy way to check that the results are correct. Example output from the script
// Trilateration example
// from Wikipedia
//
// pA, pB and pC are the centres of the spheres
// If necessary the spheres must be translated
// and rotated so that:
// -- all z values are 0
// -- pA is at the origin
pA = [0,0,0];
// -- pB is on the x axis
pB = [10,0,0];
pC = [9,7,0];
// rA , rB and rC are the radii of the spheres
rA = 9;
rB = 5;
rC = 7;
if ( pA != [0,0,0]){
echo ("ERROR: pA must be at the origin");
assert(false);
}
if ( (pB[2] !=0 ) || pC[2] !=0){
echo("ERROR: all sphere centers must be in z = 0 plane");
assert(false);
}
if (pB[1] != 0){
echo("pB centre must be on the x axis");
assert(false);
}
// show the spheres
module spheres(){
translate (pA){
sphere(r= rA, $fn = rA * 10);
}
translate(pB){
sphere(r = rB, $fn = rB * 10);
}
translate(pC){
sphere (r = rC, $fn = rC * 10);
}
}
function unit_vector( v) = v / norm(v);
ex = unit_vector(pB - pA) ;
echo(ex = ex);
i = ex * ( pC - pA);
echo (i = i);
ey = unit_vector(pC - pA - i * ex);
echo (ey = ey);
d = norm(pB - pA);
echo (d = d);
j = ey * ( pC - pA);
echo (j = j);
x = (pow(rA,2) - pow(rB,2) + pow(d,2)) / (2 * d);
echo( x = x);
// size of the cube to subtract to show
// the intersection of the spheres
cube_size = [10,10,10];
if ( ((d - rA) >= rB) || ( rB >= ( d + rA)) ){
echo ("Error Y not solvable");
}else{
y = (( pow(rA,2) - pow(rC,2) + pow(i,2) + pow(j,2)) / (2 * j))
- ( i / j) * x;
echo(y = y);
zpow2 = pow(rA,2) - pow(x,2) - pow(y,2);
if ( zpow2 < 0){
echo ("z not solvable");
}else{
z = sqrt(zpow2);
echo (z = z);
// subtract a cube with one of its corners
// at the point where the sphers intersect
difference(){
spheres();
translate ([x,y - cube_size[1],z]){
cube(cube_size);
}
}
translate ([x,y - cube_size[1],z]){
%cube(cube_size);
}
}
}

Two Rectangles intersection

I have two rectangles characterized by 4 values each :
Left position X, top position Y, width W and height H:
X1, Y1, H1, W1
X2, Y2, H2, W2
Rectangles are not rotated, like so:
+--------------------> X axis
|
| (X,Y) (X+W, Y)
| +--------------+
| | |
| | |
| | |
| +--------------+
v (X, Y+H) (X+W,Y+H)
Y axis
What is the best solution to determine whether the intersection of the two rectangles is empty or not?
if (X1+W1<X2 or X2+W2<X1 or Y1+H1<Y2 or Y2+H2<Y1):
Intersection = Empty
else:
Intersection = Not Empty
If you have four coordinates – ((X,Y),(A,B)) and ((X1,Y1),(A1,B1)) – rather than two plus width and height, it would look like this:
if (A<X1 or A1<X or B<Y1 or B1<Y):
Intersection = Empty
else:
Intersection = Not Empty
Best example..
/**
* Check if two rectangles collide
* x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
* x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
*/
boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)
{
return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}
and also one other way see this link ... and code it your self..
Should the two rectangles have the same dimensions you can do:
if (abs (x1 - x2) < w && abs (y1 - y2) < h) {
// overlaps
}
I just tried with a c program and wrote below.
#include<stdio.h>
int check(int i,int j,int i1,int j1, int a, int b,int a1,int b1){
return (\
(((i>a) && (i<a1)) && ((j>b)&&(j<b1))) ||\
(((a>i) && (a<i1)) && ((b>j)&&(b<j1))) ||\
(((i1>a) && (i1<a1)) && ((j1>b)&&(j1<b1))) ||\
(((a1>i) && (a1<i1)) && ((b1>j)&&(b1<j1)))\
);
}
int main(){
printf("intersection test:(0,0,100,100),(10,0,1000,1000) :is %s\n",check(0,0,100,100,10,0,1000,1000)?"intersecting":"Not intersecting");
printf("intersection test:(0,0,100,100),(101,101,1000,1000) :is %s\n",check(0,0,100,100,101,101,1000,1000)?"intersecting":"Not intersecting");
return 0;
}
Using a coordinate system where (0, 0) is the left, top corner.
I thought of it in terms of a vertical and horizontal sliding windows
and come up with this:
(B.Bottom > A.Top && B.Top < A.Bottom) && (B.Right > A.Left && B.Left < A.Right)
Which is what you get if you apply DeMorgan’s Law to the following:
Not (B.Bottom < A.Top || B.Top > A.Bottom || B.Right < A.Left || B.Left > A.Right)
B is above A
B is below A
B is left of A
B is right of A
If the rectangles' coordinates of the lower left corner and upper right corner are :
(r1x1, r1y1), (r1x2, r1y2) for rect1 and
(r2x1, r2y1), (r2x2, r2y2) for rect2
(Python like code below)
intersect = False
for x in [r1x1, r1x2]:
if (r2x1<=x<=r2x2):
for y in [r1y1, r1y2]:
if (r2y1<=y<=r2y2):
intersect = True
return intersect
else:
for Y in [r2y1, r2y2]:
if (r1y1<=Y<=r1y2):
intersect = True
return intersect
else:
for X in [r2x1, r2x2]:
if (r1x1<=X<=r1x2):
for y in [r2y1, r2y2]:
if (r1y1<=y<=r1y2):
intersect = True
return intersect
else:
for Y in [r1y1, r1y2]:
if (r2y1<=Y<=r2y2):
intersect = True
return intersect
return intersect
Circle approach is more straightforward. I mean when you define a circle as a center point and radius. Same thing here except you have a horizontal radius (width / 2) and a vertical one (height /2) and 2 conditions for horizontal and for vertical distance.
abs(cx1 – cx2) <= hr1 + hr2 && abs(cy1 - cy2) <= vr1 + vr2
If you need to exclude the case with sides not intersecting filter out these with one rectangle smaller in both dimensions and not enough distance (between centers) from the bigger one to reach one of its edges.
abs(cx1 – cx2) <= hr1 + hr2 && abs(cy1 - cy2) <= vr1 + vr2 &&
!(abs(cx1 – cx2) < abs(hr1 - hr2) && abs(cy1 - cy2) < abs(vr1 - vr2) && sign(hr1 - hr2) == sign(vr1 – vr2))
Rectangle = namedtuple('Rectangle', 'x y w h')
def intersects(rect_a: Rectangle, rect_b: Rectangle):
if (rect_a.x + rect_a.w < rect_b.x) or (rect_a.x > rect_b.x + rect_b.w) or (rect_a.y + rect_a.h < rect_b.y) or (rect_a.y > rect_b.y + rect_b.h):
return False
else:
return True
if( X1<=X2+W2 && X2<=X1+W1 && Y1>=Y2-H2 && Y2>=Y1+H1 )
Intersect
In the question Y is the top position..
Note: This solution works only if rectangle is aligned with X / Y Axes.

Resources