Search code examples
geometrycomputational-geometryintersection

Intersection between AABB and a capsule (swept sphere)


I have an axis aligned bounding box in R3 space defined by minimum vector A and maximum vector B, and a capsule defined by a segment with end points a and b, and radius r. I would like to check if the two shapes intersect.

I know that the two shapes do in fact intersect if the capsule's defining segment intersects the AABB. However how do I handle the remaining case where the segment does not intersect the AABB, but the capsule still does.


Solution

  • Popular physics engines like Bullet use GJK algorithm for intersections between convex shapes (except for simple ones). And since there doesn't seem to be easy solution for this intersection, and I needed to implement more intersections for shapes like cylinders, cones, capsules, boxes, I decided to go with the GJK approach. You have to implement it once, and then you can check for intersection between any two convex shapes, by just defining support function for that shape.

    Support functions for some common shapes are described here. And here is the excerpt for the support function of a capsule:

    struct Capsule : Collider {
        float r, y_base, y_cap;
    
        vec3 support(vec3 dir){
            dir = matRS_inverse*dir; //find support in model space
    
            vec3 result = normalise(dir)*r;
            result.y += (dir.y>0) ? y_cap : y_base;
    
            return matRS*result + pos; //convert support to world space
        }
    };