Advertisement
Guest User

Rotated rectangle collision in Dart

a guest
Oct 18th, 2013
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. //Dart Implementation for detecting collision of two rotated rectangles
  2.  
  3. class Collision {
  4.   static bool collides(CollisionBox a, CollisionBox b) {
  5.     //The getpoints function will return the coordinates of the box in this order:
  6.     //0:topleft  1:topright  2:bottomright   3: bottomleft
  7.  
  8.     List<Vector2> A = a.getPoints();
  9.     List<Vector2> B = b.getPoints();
  10.  
  11.     Vector2 Axis1 = new Vector2(A[1].x-A[0].x,A[1].y-A[0].y);
  12.     Vector2 Axis2 = new Vector2(A[1].x-A[2].x,A[1].y-A[2].y);
  13.     Vector2 Axis3 = new Vector2(B[0].x-B[3].x,B[0].y-B[3].y);
  14.     Vector2 Axis4 = new Vector2(B[0].x-B[1].x,B[0].y-B[1].y);
  15.    
  16.     return _projectionOverlap(Axis1,A,B) &&
  17.         _projectionOverlap(Axis2,A,B) &&
  18.         _projectionOverlap(Axis3,A,B) &&
  19.         _projectionOverlap(Axis4,A,B);
  20.   }
  21.  
  22.   static bool _projectionOverlap (Vector2 v,List<Vector2> A, List<Vector2> B) {
  23.     List aVal = _projectPoints(v,A);
  24.     double aMin = aVal[0];
  25.     double aMax = aVal[1];
  26.    
  27.     List bVal = _projectPoints(v,B);
  28.     double bMin = bVal[0];
  29.     double bMax = bVal[1];
  30.    
  31.     if (aMax < bMin || bMax < aMin)
  32.       return false;
  33.     else
  34.       return true;
  35.   }
  36.  
  37.   static List _projectPoints(Vector2 v, List<Vector2> A) {
  38.     double aMin;
  39.     double aMax;
  40.     A.forEach((Vector2 p) {
  41.       num val = (p.x*v.x)+(p.y*v.y); //dot product of p & v
  42.      
  43.       if (aMin == null) {
  44.         aMin = val;
  45.         aMax = val;
  46.       } else {
  47.         aMin = Math.min(val, aMin);
  48.         aMax = Math.max(val, aMax);
  49.       }
  50.      
  51.     });
  52.    
  53.     return [aMin,aMax];
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement