/* Read http://z0b.kapsi.fi/snippets.php before using this code. Thank you. */ float distanceFromPointToAABB(const math::vec3 &min, const math::vec3 &max, const math::vec3 &p) { // if the point is inside the box, return zero if (p.x >= min.x && p.x <= max.x && p.y >= min.y && p.y <= max.y && p.z >= min.z && p.z <= max.z) return 0.0f; // clamp the point inside the min/max box points math::vec3 test = p; for (size_t i = 0; i < 3; i++) { if (test[i] < min[i]) test[i] = min[i]; if (test[i] > max[i]) test[i] = max[i]; } return p.distance(test); }