Advertisement
professor_craven

Polygon Collision

Dec 26th, 2015
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. class Point {
  2.     public double x;
  3.     public double y;
  4.     public Point(double x, double y) {
  5.         this.x = x;
  6.         this.y = y;
  7.     }
  8. }
  9.  
  10. class Polygon {
  11.     public Point [] points;
  12.     public Point [] getPoints() {
  13.         return points;
  14.     }
  15. }
  16.  
  17. class Test {
  18.  
  19.     static boolean isPolygonsIntersecting(Polygon a, Polygon b)
  20.     {
  21.         for (int x=0; x<2; x++)
  22.         {
  23.             Polygon polygon = (x==0) ? a : b;
  24.  
  25.             for (int i1=0; i1<polygon.getPoints().length; i1++)
  26.             {
  27.                 int   i2 = (i1 + 1) % polygon.getPoints().length;
  28.                 Point p1 = polygon.getPoints()[i1];
  29.                 Point p2 = polygon.getPoints()[i2];
  30.  
  31.                 Point normal = new Point(p2.y - p1.y, p1.x - p2.x);
  32.  
  33.                 double minA = Double.MAX_VALUE;
  34.                 double maxA = Double.MIN_VALUE;
  35.  
  36.                 for (Point p : a.getPoints())
  37.                 {
  38.                     double projected = normal.x * p.x + normal.y * p.y;
  39.  
  40.                     if (projected < minA)
  41.                         minA = projected;
  42.                     if (projected > maxA)
  43.                         maxA = projected;
  44.                 }
  45.  
  46.                 double minB = Double.MAX_VALUE;
  47.                 double maxB = Double.MIN_VALUE;
  48.  
  49.                 for (Point p : b.getPoints())
  50.                 {
  51.                     double projected = normal.x * p.x + normal.y * p.y;
  52.  
  53.                     if (projected < minB)
  54.                         minB = projected;
  55.                     if (projected > maxB)
  56.                         maxB = projected;
  57.                 }
  58.  
  59.                 if (maxA < minB || maxB < minA)
  60.                     return false;
  61.             }
  62.         }
  63.  
  64.         return true;
  65.     }
  66.  
  67.     public static void main(String args[]) {
  68.         System.out.println("Test");
  69.         Polygon p1 = new Polygon();
  70.         Polygon p2 = new Polygon();
  71.         p1.points = new Point[]{new Point( 0.235, 0.305), new Point(0.485, 0.305), new Point( 0.235, 0.495), new Point(0.485, 0.495)};
  72.         p2.points = new Point[]{new Point(-0.125, 0.405), new Point(0.125, 0.405), new Point(-0.125, 0.595), new Point(0.125, 0.595)};
  73.         boolean result = isPolygonsIntersecting(p1, p2);
  74.         System.out.println(result);
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement