'Overlapped Area between two Colliders

Image here.

In the above Image there are two Cubes with a Rigidbody and a BoxCollider attached to each of them. Let's say we have an animation in which the cube on top moves and overlaps the cube which is below it. The Cube on top moves some distance on y-axis and the cube below doesn't move. How do I calculate the yellow area,i.e, the area which shows overlapping?

Thank You.



Solution 1:[1]

Assuming these are always cubes and world axis aligned you could probably simply do

public Vector3 OverlapArea(BoxCollider a, BoxCollider b)
{
    // get the bounds of both colliders
    var boundsA = a.bounds;
    var boundsB = b.bounds;

    // first heck whether the two objects are even overlapping at all
    if(!boundsA.Intersects(boundsB))
    {
        Vector3.zero;
    }

    // now that we know they at least overlap somehow we can calculate

    // get the bounds of both colliders
    var boundsA = a.bounds;
    var boundsB = b.bounds;

    // get min and max point of both
    var minA = boundsA.min; (basically the bottom-left-back corner point)
    var maxA = boundsA.max; (basically the top-right-front corner point)

    var minB = boundsB.min;
    var maxB = boundsB.max;

    // we want the smaller of the max and the higher of the min points
    var lowerMax = new Vector3.Min(maxA, maxB);
    var higherMin = new Vector3.Max(minA, minB);

    // the delta between those is now your overlapping area
    return lowerMax - higherMin;
}

and if you want the area in as usual just do

var overlap = OverlapArea(colliderA, colliderB);
var overlapArea = overlap.x * overlap.y * overlap.z;

See


Anything beyond that (rotated and differently shaped objects) would probably fit better for the Mathematics community

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1