Advertisement
tomasslavicek

OBB vs. OBB collision

Dec 30th, 2013
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. /// <summary>
  2. /// 4 body orientovaného obdélníku
  3. /// - top-left, top-right, bottom-right, bottom-left !!! (clockwise order)
  4. /// </summary>
  5.  
  6.  
  7. /// <summary>
  8. /// Test kolize - jestli dva orientované rectangles (ve světových souřadnicích) kolidují
  9. /// </summary>
  10. public static bool IsCollidingRectangles(Vector2[] a, Vector2[] b)
  11. {
  12.     if (!CollidesWith(a, b)) // Všechny 4 body b jsou za nějakou stranou a (tj. určitě není kolize)
  13.         return false;
  14.     if (!CollidesWith(b, a))
  15.         return false;
  16.     return true;
  17. }
  18.  
  19. /// <summary>
  20. /// Jestli koliduje a -> b (pak se testuje i obráceně...)
  21. /// </summary>
  22. public static bool CollidesWith(Vector2[] a, Vector2[] b)
  23. {
  24.     for (int i = 0; i < 4; i++)
  25.     {
  26.         int j = (i + 1) % 4;
  27.         Vector2 vectorStart = a[j];
  28.         Vector2 vectorDirection = a[i] - a[j];
  29.  
  30.         bool collisionFound = false;
  31.         for (int y = 0; y < 4; y++)
  32.             if (IsPointOnRightSide(vectorStart, vectorDirection, b[y]))
  33.                 collisionFound = true;
  34.  
  35.         if (!collisionFound)
  36.             return false;
  37.     }
  38.     return true;
  39. }
  40.  
  41. /// <summary>
  42. /// Tests line (vector + point) vs. other point
  43. /// - vectorDirection = LinePoint1 - VectorStart   (VectorStart = LinePoint2)
  44. /// - returns true, if the point is on the right side of the line
  45. /// </summary>
  46. private static bool IsPointOnRightSide(Vector2 vectorStart, Vector2 vectorDirection, Vector2 point)
  47. {
  48.     Vector2 secondVector = point - vectorStart;
  49.     float dotProduct = Vector2.Dot(vectorDirection, secondVector); // = skalární součin
  50.     return dotProduct > 0f;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement