- Home /
Dynamically creating a box collider for an object with multiple, rotated, and scaled mesh renderers
Ok, here's the desired functionality: The script should be able to take in a single gameObject with at least one renderer attached to it, or one of its children. The script then removes all instances of boxColliders (FindComponentsInChildren with a Destroy(...) loop). So far, pretty easy. Then, I want to grab all instances of mesh-renderers (FindComponentsInChildren()) and add each one to a new bounds (using bounds.encapsulate so far). I use these bounds for transformation functions (calculating the distance between the anchor point and the floor, etc), and I also use them to create a single BoxCollider on the parent of the GameObject which should perfectly encapsulate the "smallest box that contains all mesh elements".
Here's the issue: bounds.encapsulate assumes that every single child object is scaled to (1,1,1) and rotated to (0,0,0).
Previously, I've tried grabbing all child Transforms, parenting them to the top parent of the GameObject, and then simply scaling their MeshFilter.sharedMesh.bounds by their localScale. This will not work, however, as some objects contain Animations which make the object instantly unrecognizable when all its parts are re-childed to the GameObject transform.
private void GrabBounds() //returns a bounds that encapsulates all renderers on all children
{
MeshFilter this_mf = GetComponent<MeshFilter>();
if (this_mf == null)
{
bounds = new Bounds(Vector3.zero, Vector3.zero);
}
else
{
bounds = this_mf.sharedMesh.bounds;
}
MeshFilter[] mfs = GetComponentsInChildren<MeshFilter>();
foreach (MeshFilter mf in mfs)
{
if (mf != GetComponent<MeshFilter>())
{
Vector3 pos = mf.transform.localPosition;
Bounds child_bounds = mf.sharedMesh.bounds;
child_bounds = ScaleChildBounds(child_bounds, mf.transform);
child_bounds.center += pos;
bounds.Encapsulate(child_bounds);
}
}
}
private Bounds ScaleChildBounds(Bounds _childBounds, Transform _child)
{
Bounds bounds = _childBounds;
Vector3 boundExtents = bounds.extents;
boundExtents.x *= _child.localScale.x;
boundExtents.y *= _child.localScale.y;
boundExtents.z *= _child.localScale.z;
bounds.extents = boundExtents;
Transform parent = _child.parent;
while(parent != null)
{
boundExtents.x *= parent.localScale.x;
boundExtents.y *= parent.localScale.y;
boundExtents.z *= parent.localScale.z;
parent = parent.parent;
}
bounds.extents = boundExtents;
return bounds;
}
Note: this code is not yet even attempting to take into account childObject rotation issues.