Advertisement
Chronos_Ouroboros

TestSphereAABB

Jun 19th, 2019
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1.     static bool TestSphereAABB (Vector3 sphereCoords, double sphereRadius, Vector3 boxCoords, Vector2 boxSize) {
  2.         // Compute squared distance between sphere center and AABB
  3.         // the sqrt (dist) is fine to use as well, but this is faster.
  4.         float sqDist = 0.0f;
  5.  
  6.         let diffCoords = level.Vec3Diff (sphereCoords, boxCoords);
  7.  
  8.         let bMin = (
  9.             diffCoords.X - boxSize.X,
  10.             diffCoords.Y - boxSize.X,
  11.             diffCoords.Z
  12.         );
  13.         let bMax = (
  14.             diffCoords.X + boxSize.X,
  15.             diffCoords.Y + boxSize.X,
  16.             diffCoords.Z + boxSize.Y
  17.         );
  18.  
  19.         // For each axis count any excess distance outside box extents
  20.         // X
  21.         if (bMin.X > 0) sqDist += (bMin.X) * (bMin.X);
  22.         if (bMax.X < 0) sqDist += (bMax.X) * (bMax.X);
  23.         // Y
  24.         if (bMin.Y > 0) sqDist += (bMin.Y) * (bMin.Y);
  25.         if (bMax.Y < 0) sqDist += (bMax.Y) * (bMax.Y);
  26.         // Z
  27.         if (bMin.Z > 0) sqDist += (bMin.Z) * (bMin.Z);
  28.         if (bMax.Z < 0) sqDist += (bMax.Z) * (bMax.Z);
  29.  
  30.         // Sphere and AABB intersect if the (squared) distance between them is
  31.         // less than the (squared) sphere radius.
  32.         return sqDist <= sphereRadius * sphereRadius;
  33.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement