Say I have an array of Polygons expressed as an array of an array [x,y]
values, for example:
var polygons = [
[
[8, 57],
[15, 57],
[15, 71],
[8, 71],
[8, 57]
], [
[77, 36],
[85, 36],
[85, 50],
[77, 50],
[77, 36]
]
]
And I have a line like so:
var line = [[8,5], [92, 78]]
How can I get a list of the indexes of polygons that intersect with the line, if there are none, then return 0?
Here is an illustration. This does not match the polygons and the line, but should give you an understanding of the environment. With this example, it should return [0] (assuming the polygon that it intersects with is the first in the polygon list):
I am not sure how to approach this problem, and have searched elsewhere on the internet but could only find a function that works with squares. These are polygons, so it doesn’t really work.
2
Answers
Suggested strategy
var line
. If it does, then that polygon is crossed by the line, and you don’t need to consider any more points on that polygon.How to tell if 2 line segments intersect?
Nice answers given here:
https://stackoverflow.com/a/563275/7549483
I ported the following code over to JavaScript:
And adapted it to your data structures.