- Home /
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 or quadrilateral.
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).
My absolute gratitude in advance!
- S. Darkwell
Answer by S_Darkwell · Apr 16, 2015 at 12:46 PM
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[i] > region.center[i] ?
obj.max[i] - region.max[i] :
region.min[i] - obj.min[i];
total *= Mathf.Clamp01(1f - dist / obj.size[i]);
}
return total;
}
I hope that others may find the above helpful!
I don't want to be a killjoy, but it seems you'll need some sort of zero division check. I only noticed this trying it on a 2D object, since these still have their size defined in a Vector3 though z-size is 0.
This check will also be relevant if you animate or in other ways manipulate your objects to possibly reach a zero thickness in any one direction. Since my need for this only applied to 2D objects, I just went with i [0;1], i.e.
for (int i = 0; i < 2; i++)
but just add a check and you'll be fine to use it more generically ;)
$$anonymous$$asperCEGO could you please explain some more and maybe give an example of what should be done to make this work for 2D objects? Thanks
Your answer
![](https://koobas.hobune.stream/wayback/20220613192505im_/https://answers.unity.com/themes/thub/images/avi.jpg)