• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Point-Polygon-Collision.py Nightdra  Mar 24th, 2019 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. def infhorizline_line(a, b, count_overlap=True):
2.     """
3.    returns 0 for no intersection
4.    returns 1 for an intersection to the left of point a (if the point of intersection is on a, this is the default)
5.    returns 2 for an intersection to the right of point a
6.    """
7.     # Check if b is horizontal
8.     if b == b:
9.         if count_overlap:
10.             # Not perfect... not used so will do
11.             if b == a:
12.                 if a <= b: return 1
13.                 elif a >= b: return 2
14.         return 0
15.
16.     # Edge case for polygonal collision so the intersection between two lines is only counted once unless it is a local minima or maxima
17.     # in which case it will be counted two or zero times
18.     if b >= b: highb = b; lowb = b
19.     else: highb = b; lowb = b
20.     if highb == a:
21.         if a <= highb: return 1
22.         else: return 2
23.     if lowb == a: return 0
24.
25.
26.     # Check if the points of b are on opposite sides of line a
27.     if (b >= a and b <= a) or (b <= a and b >= a):
28.         # Check if b is vertical
29.         if b == b:
30.             poi = b
31.         else:
32.             slope = (b-b) / (b-b)
33.             poi = (a-b)/slope + b
34.         if a <= poi: return 1
35.         else: return 2
36.     return 0
37.
38. def point_polygon(point, polygon):
39.     # Algorithm works by creating a horizontal line at the y-level of the point to intersect with the lines of the polygon.
40.     # If the number of intersections on the left (or right) of the polygon is odd, then the point lies within the polygon/
41.     # If the number of intersections on the left (or right) or the polygon is even, then the point lies outside of the polygon
42.     poly = polygon[:] + [polygon]
43.     line_intersections = [0,0]
44.     for i in range(len(poly)-1):
45.         intersect = infhorizline_line(point, [poly[i],poly[i+1]], count_overlap=False)
46.         if intersect: line_intersections[intersect-1] += 1
47.     return line_intersections%2 != 0
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Not a member of Pastebin yet?