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[0][1] == b[1][1]:
  9.         if count_overlap:
  10.             # Not perfect... not used so will do
  11.             if b[0][1] == a[1]:
  12.                 if a[0] <= b[0][0]: return 1
  13.                 elif a[0] >= b[0][0]: 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[0][1] >= b[1][1]: highb = b[0]; lowb = b[1]
  19.     else: highb = b[1]; lowb = b[0]
  20.     if highb[1] == a[1]:
  21.         if a[0] <= highb[0]: return 1
  22.         else: return 2
  23.     if lowb[1] == a[1]: return 0
  24.  
  25.  
  26.     # Check if the points of b are on opposite sides of line a
  27.     if (b[0][1] >= a[1] and b[1][1] <= a[1]) or (b[0][1] <= a[1] and b[1][1] >= a[1]):
  28.         # Check if b is vertical
  29.         if b[0][0] == b[1][0]:
  30.             poi = b[0][0]
  31.         else:
  32.             slope = (b[1][1]-b[0][1]) / (b[1][0]-b[0][0])
  33.             poi = (a[1]-b[0][1])/slope + b[0][0]
  34.         if a[0] <= 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[0]]
  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[0]%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. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top