# How to detect how far another collider is intersecting another!

I am using OnCollisionStay () to find out how far an object is colliding into another. If it is colliding more than it should be then it will send another script a message saying it can’t be placed.
Code:

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClippingDetector : MonoBehaviour {

private Structure structure;
private Bounds structureBounds;

void Awake () {
structure = GetComponent<Structure> ();
structure.QueryCollisions ();
structureBounds = structure.GetComponent<Collider> ().bounds;
}

public void OnCollisionStay (Collision coll) {
if (coll.gameObject.GetComponent<Structure> () != null && coll.gameObject.GetComponent<Structure> ().strictCollisions && layerMask == (layerMask.value | 1<<coll.gameObject.layer)) { // Its a structure and has strict collisions
structureBounds = new Bounds (structureBounds.center, structureBounds.size * .95f); // New bounds
} else {
structureBounds = new Bounds (structureBounds.center, structureBounds.size * .8f); // New bounds
}
if (coll.collider.bounds.Intersects (structureBounds) && coll.collider.tag == "Structure") {
structure.CollisionEnter (coll.gameObject);
}
}

public void OnCollisionExit (Collision coll) {
structure.CollisionExit (coll.gameObject);
}
}
``````

Alas, this problem is not quite a simple as it sounds. Mostly because of the possible variation in the SHAPE of your objects. I see you use bounding boxes, which might be fine approximation, but will be very limited in accuracy. Consider a 3d plus sign; with this shape the bounding box corner might intersect something, even if the plus-sign does not.

Computing the overlap/intersection volume of two arbitrary meshes is a pretty complex operation, usually employing lots of line/plane or triangle/triangle intersection tests. (here is a good resource on that stuff: Object/Object Intersection)

The additional difficulty with using bounding boxes, is that they don’t rotate: they are always an axis-aligned box.

Given the above limitations, will using the bound box be sufficient for your needs?

If so, once you have confirmed the bounding boxes intersect, you will need to:

``````  loop through all the corners points of bounds A
if this point intersect bound B ( use Bounds.Contains to test)
loop though all the FACES/planes of bounds B
compute the distance between our intersecting bound A corner, and the current bound B face
keep the largest distance value computed (this is your intersection depth)
``````

(I was hoping Bounds.SqrDistance would work for this, rather than having to loop, but that only seems to work for vectors OUTSIDE the bounds. Passing vectors “Contained” inside the bounds, returns 0.)