How to calculate closest distance between two AABBs (vector form)?

1.4k views Asked by At

How to calculate closest distance between two AABBs (vector form)? I found a solution here. Is it possible extract a vector form of this? I know a vector form of AABB - point distance.

Candidate:

Float distance(const Box & a, const Box & b) {
    return Vector::zero.max(a.min - b.max).max(b.min - a.max).magnitude();
}
1

There are 1 answers

0
Fedor On

The distance between two axis-aligned bounding boxes (AABB) can be computed as follows:

  1. 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.

  1. 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.