- Home /
Calculate shortest distance between two objects
How can I get the distance between two objects when one of them is really big (e.g. a wall) and the other one is kinda small? I am aware of vector3.distance but I can't use that, because it uses the world coordinates. It's like calculating the distance on only one axe, but without knowing the axe.
I hope you can help me :)
I'm unclear about what you are asking. Given you are talking about a wall, Collider.ClosestPointOnBounds() might be the solution you are looking for..
You could also get your vertices of each object and get the closest vertex form object A to position of object B, do the same the other way around and get distance between your two found vertices.
Answer by robhuhn · Sep 19, 2013 at 10:50 AM
Sounds like you need a Point-to-plane distance - For that you could use this method (c#)
float distance = PointToPlaneDistance(smallObj.transform.position, wall.transform.position, wallNormal);
private float PointToPlaneDistance(Vector3 pointPosition, Vector3 planePosition, Vector3 planeNormal)
{
float sb, sn, sd;
sn = -Vector3.Dot(planeNormal, (pointPosition - planePosition));
sd = Vector3.Dot(planeNormal, planeNormal);
sb = sn / sd;
Vector3 result = pointPosition + sb * planeNormal;
return Vector3.Distance(pointPosition, result);
}
Thanks for your help, but what is wall-/planeNormal? Where do I get that 3rd Vector from?
If you meant, that the 3rd Vector should be the 2nd one but normalized, than it is not working. I'm still getting different Values for the distance.
The normal is not the normalized vector but the normal of the walls surface (surface normal).
It was a bit complicated to find out how to calculate the normal of the wall, but it worked. Thanks a lot :)
Your answer
Follow this Question
Related Questions
Check distance between multiple objects 1 Answer
Decrease value at half the speed it's increased at? (using Vector3.Distance) 1 Answer
how to create an outlined polygon with vector3 coordinates? 0 Answers
Multiple Cars not working 1 Answer
Calculate the distance between an object and my player 1 Answer