Advertisement
professor_craven

Collision between polygons

Dec 26th, 2015
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. class Point():
  2.     def __init__(self, x, y):
  3.         self.x = x
  4.         self.y = y
  5.  
  6.     def __str__(self):
  7.         return "({}, {})".format(self.x, self.y)
  8.  
  9.     def __repr__(self):
  10.         return "({}, {})".format(self.x, self.y)
  11.  
  12. def are_polygons_intersecting(poly_a, poly_b):
  13.  
  14.     for polygon in (poly_a, poly_b):
  15.         #print("\nPolygon")
  16.  
  17.         for i1 in range(len(polygon)):
  18.             i2 = (i1 + 1) % len(polygon)
  19.             #print("i1={} i2={}".format(i1, i2))
  20.             p1 = polygon[i1]
  21.             p2 = polygon[i2]
  22.  
  23.             normal = Point(p2.y - p1.y, p1.x - p2.x)
  24.  
  25.             minA, maxA, minB, maxB = (None,) * 4
  26.  
  27.             for p in poly_a:
  28.                 projected = normal.x * p.x + normal.y * p.y
  29.  
  30.                 if not minA or projected < minA:
  31.                     minA = projected
  32.                 if not maxA or projected > maxA:
  33.                     maxA = projected
  34.  
  35.             for p in poly_b:
  36.                 projected = normal.x * p.x + normal.y * p.y
  37.  
  38.                 if not minB or projected < minB:
  39.                     minB = projected
  40.                 if not maxB or projected > maxB:
  41.                     maxB = projected
  42.  
  43.             #print("maxA={} minB={} -- maxB={} minA={}".format(minA, minB, maxA, maxB))
  44.             if maxA < minB or maxB < minA:
  45.                 return False
  46.  
  47.     return True
  48.  
  49. p1 = (Point(0.235, 0.305), Point(0.485, 0.305), Point(0.235, 0.495), Point(0.485, 0.495))
  50. p2 = (Point(-0.125, 0.405), Point(0.125, 0.405), Point(-0.125, 0.595), Point(0.125, 0.595))
  51. r = are_polygons_intersecting(p1, p2)
  52. print(r)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement