- Home /
Calculate Distance between 2 colliders
I'm trying, unsuccessfully, to find a way to easily calculate the distance between two objects's collider. In my case I'm trying between two box collider,
BoxCollider boxColStart = start.GetComponent<BoxCollider>();
Vector3 centerBoxStart = boxColStart.ClosestPointOnBounds(end.transform.position);
BoxCollider boxColEnd = end.GetComponent<BoxCollider>();
Vector3 centerBoxEnd = boxColEnd.ClosestPointOnBounds(start.transform.position);
lineRenderer.SetPosition (0, centerBoxStart);
lineRenderer.SetPosition (1, centerBoxEnd);
the code I'm using is wrong and this sketch is the proof:
every suggestion is very welcome
Thanks
Davide
You should try Physic.Raycast from start to end and from end to start (http://docs.unity3d.com/ScriptReference/Physics.Raycast.html)
you may be more explicative such as the steps to do? :)
Use a raycast from start object to end object to get the hit collision point on end face object. Use an another raycast from end object to start object to get the hit collision point on start face object. Compute the distance between the two hit point. It won't give you exact result but it should give you a more precise distance. If it's not enough http://gamedev.stackexchange.com/questions/6750/easiest-way-to-compute-closest-point-between-two-triangular-meshes
$$anonymous$$eep doing closestpointonbounds with the results you get from doing that until the closest points no longer change?
If they don't rotate, use their positions, their bounds extends and calculate the distance with them. If they rotate, watermy's suggestion is probably the easiest.
Answer by Ericool · Mar 24, 2015 at 04:14 PM
look in collider.bounds.center instead it gives a vector3
Answer by mojtaba1995 · Aug 05, 2016 at 04:29 PM
If your collider is set on your mesh you can find the distance between meshes using vertices and etc. see link below for more (first one is for 2d meshes and the next is for 3d ) https://www.youtube.com/watch?v=R_kV3YiJqEw // https://www.youtube.com/watch?v=642o94MNfs4
Your answer