The distance between two axis-aligned bounding boxes (AABB) can be computed as follows:
- Find the intersection box of two input boxes, which can be expressed in C++:
Box Box::intersection( const Box & b ) const
{
Box res;
for ( int i = 0; i < V::elements; ++i )
{
res.min[i] = std::max( min[i], b.min[i] );
res.max[i] = std::min( max[i], b.max[i] );
}
return res;
}
where min
and max
are two corner points of a box.
- Then the squared distance between two boxes is:
T Box::getDistanceSq( const Box & b ) const
{
auto ibox = intersection( b );
T distSq = 0;
for ( int i = 0; i < V::elements; ++i )
if ( ibox.min[i] > ibox.max[i] )
distSq += sqr( ibox.min[i] - ibox.max[i] );
return distSq;
}
The function returns zero if input boxes touch or intersect.
The code above was taken from MeshLib and it works both for 2D (V::elements=2
) and 3D (V::elements=3
).
It is not quite clear what you mean by "vector form", since the distance is a scalar. If one wants a more concise implementation of getDistanceSq
, then in addition to intersection
the second part of the function can be named somehow.