Percentage of Collider within a Trigger Area (C#)

Hello fellow Unity Developers,

I am attempting to create a C# function that linearly interpolates a Rigidbody’s drag based upon the percentage of the Rigidbody’s collider that is within a trigger collider “Water Region”.

Considerations:

• Water Regions will likely be
convex and with relatively simple
geometry, but they may sometimes be
spherical and may not always be regular
• The Rigidbody may enter the Water
Region from any point and may be
facing any direction while doing so.

While I am certain such is possible via a series of Bounds.Contains() checks, this would not be performant and would have a resolution limited by the number points being checked.

Is there an efficient or mathematical means of determining what percentage of a Collider is within a trigger zone?

Even partial solutions are absolutely welcome (eg: only works with rectangular / spherical Water Regions).

- S. Darkwell

Below is a simplistic solution. It treats both the object and the region that the object is being tested against as quadrangles, but for the time being, it works for my purposes:

``````/// <summary>
/// Returns the percentage of obj contained by region. Both obj and region are calculated as quadralaterals for performance purposes.
/// </summary>
/// <param name="obj"></param>
/// <param name="region"></param>
/// <returns></returns>
private float BoundsContainedPercentage( Bounds obj, Bounds region )
{
var total = 1f;

for ( var i = 0; i < 3; i++ )
{
var dist = obj.min _> region.center *?*_
``````

obj.max - region.max :
region.min - obj.min*;*

total = Mathf.Clamp01(1f - dist / obj.size);*
}