Expand a collider until it full contains another collider
I have referred to several other answers on a similar subject but with no luck. I am trying to expand the width of a collider until it fully contains the other collider but bounds.Contains is never returning true. Please help.
private IEnumerator ExpandCollider(BoxCollider col, GameObject obj)
{
Vector3[] bounds = GetVerteciesPositions(obj);
while (!isInside(col, bounds))
{
col.size = new Vector3(col.size.x, col.size.y + 0.01f, col.size.z);
if (col.size.y > 50)
{
break;
}
}
yield return null;
}
private bool isInside(BoxCollider col, Vector3[] Bounds)
{
bool inside = true;
for (int i = 0; i < Bounds.Length; i++)
{
if (inside)
{
//Vector3 localPos = col.transform.InverseTransformPoint(new Vector3 (Mathf.Abs(Bounds[i].x), Mathf.Abs(Bounds[i].y), Mathf.Abs(Bounds[i].z)));
//inside = Mathf.Abs(localPos.x) < 0.5f && Mathf.Abs(localPos.y) < 0.5f && Mathf.Abs(localPos.z) < 0.5f;
inside = col.bounds.Contains(new Vector3(Mathf.Abs(Bounds[i].x), Mathf.Abs(Bounds[i].y), Mathf.Abs(Bounds[i].z)));
}
else
{
return false;
}
}
return inside;
}
private Vector3[] GetVerteciesPositions(GameObject obj)
{
Vector3[] vertices = new Vector3[8];
Matrix4x4 thisMatrix = obj.transform.localToWorldMatrix;
Quaternion storedRotation = obj.transform.rotation;
obj.transform.rotation = Quaternion.identity;
BoxCollider col = obj.GetComponent<BoxCollider>();
Vector3 extents = col.bounds.extents;
vertices[0] = thisMatrix.MultiplyPoint3x4(extents);
vertices[1] = thisMatrix.MultiplyPoint3x4(new Vector3(-extents.x, extents.y, extents.z));
vertices[2] = thisMatrix.MultiplyPoint3x4(new Vector3(extents.x, extents.y, -extents.z));
vertices[3] = thisMatrix.MultiplyPoint3x4(new Vector3(-extents.x, extents.y, -extents.z));
vertices[4] = thisMatrix.MultiplyPoint3x4(new Vector3(extents.x, -extents.y, extents.z));
vertices[5] = thisMatrix.MultiplyPoint3x4(new Vector3(-extents.x, -extents.y, extents.z));
vertices[6] = thisMatrix.MultiplyPoint3x4(new Vector3(extents.x, -extents.y, -extents.z));
vertices[7] = thisMatrix.MultiplyPoint3x4(-extents);
obj.transform.rotation = storedRotation;
return vertices;
}
Comment
I realised in the isInside check it was not putting the bounds into the local space of the collider so this is working partially:
private bool isInside(BoxCollider col, Vector3[] Bounds)
{
bool inside = true;
for (int i = 0; i < Bounds.Length; i++)
{
if (inside)
{
inside = (col.bounds.Contains(transform.InverseTransformPoint(Bounds[i])));
}
else
{
return false;
}
}
return inside;
}
However it's working perfectly at 45 degrees and at other angles giving completely incorrect sizes, maybe this is to do with the rotation because bounds are axis alligned right?