Advertisement
sriharshachilakapati

Java Polygon Intersection test

Dec 4th, 2014
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. boolean isPolygonsIntersecting(Polygon a, Polygon b)
  2. {
  3.     for (int x=0; x<2; x++)
  4.     {
  5.         Polygon polygon = (x==0) ? a : b;
  6.        
  7.         for (int i1=0; i1<polygon.getPoints().length; i1++)
  8.         {
  9.             int   i2 = (i1 + 1) % polygon.getPoints().length;
  10.             Point p1 = polygon.getPoints()[i1];
  11.             Point p2 = polygon.getPoints()[i2];
  12.            
  13.             Point normal = new Point(p2.y - p1.y, p1.x - p2.x);
  14.            
  15.             double minA = Double.MAX_VALUE;
  16.             double maxA = Double.MIN_VALUE;
  17.            
  18.             for (Point p : a.getPoints())
  19.             {
  20.                 double projected = normal.x * p.x + normal.y * p.y;
  21.                
  22.                 if (projected < minA)
  23.                     minA = projected;
  24.                 if (projected > maxA)
  25.                     maxA = projected;
  26.             }
  27.            
  28.             double minB = Double.MAX_VALUE;
  29.             double maxB = Double.MIN_VALUE;
  30.            
  31.             for (Point p : b.getPoints())
  32.             {
  33.                 double projected = normal.x * p.x + normal.y * p.y;
  34.                
  35.                 if (projected < minB)
  36.                     minB = projected;
  37.                 if (projected > maxB)
  38.                     maxB = projected;
  39.             }
  40.            
  41.             if (maxA < minB || maxB < minA)
  42.                 return false;
  43.         }
  44.     }
  45.    
  46.     return true;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement