For a given rectangle R1
I am trying to find out which are the other rectangles that could intersect with it IF I draw a vectical line segment.
The rectangles that intersect with R1
are marked in Red.
Every rectangle is characterized by its (top, left)
and (bottom, right)
coordinates.
R1 = [top, left, bottom, right],...,Rn = [top, left, bottom, right]
By using the coordinates and the vertical line. I want to find the rectangles that intersects with R1
I found the following library which does the same work as the icl boost library but must simpler: download site: [ https://github.com/ekg/intervaltree][2]
#include <iostream>
#include <fstream>
#include "IntervalTree.h"
using namespace std;
struct Position
{
int x;
int y;
string id;
};
int main()
{
vector<Interval<Position>> intervals;
intervals.push_back(Interval<Position>(4,10,{1,2,"r1"}));
intervals.push_back(Interval<Position>(6,10,{-6,-3,"r2"}));
intervals.push_back(Interval<Position>(8,10,{5,6,"r3"}));
vector<Interval<Position> > results;
vector<string> value;
int start = 4;
int stop = 10;
IntervalTree<Position> tree(intervals);
// tree.findContained(start, stop, results);
tree.findOverlapping(start, stop, results);
cout << "found " << results.size() << " overlapping intervals" << endl;
}
intervals.push_back(Interval(4,10,{1,2,"r1"}));
Your need a collision detection algorithm. In C++ there's boost.geometry for doing such things among many others.
You don't care where the rectangles are vertically. You can project everything onto the x-axis and then solve the corresponding 1-dimensional problem: you have a set of intervals and you want to know which overlap with a given interval. This is exactly what an interval tree is does:
Where:
Pseudo Code
// make sure x1 is on the left of x2
if (R.x1 > R.x2)
tmp = R.x2
R.x2 = R.x1
R.x1 = tmp
end if
for each Rect as r
// don't test itself
if (R != r)
// make sure x1 is on the left of x2
if (r.x1 > r.x2)
tmp = r.x2
r.x2 = r.x1
r.x1 = tmp
end if
if ((r.x2 < R.x1) // if r rect to left of R rect
|| (r.x1 > R.x2)) // if r rect to right of R rect
// r rect does not intersect R rect
else
// r rect does intersect R rect
end if
end if
end for
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.