Reputation: 541
Hello2,
I have a (might be a really simple) question that I cannot figure out.
How do i measure a distance between two object - visually not mathematically?
I know that i can use Vector3.Distance to measure the object's distance.
but its not what I am looking for.
To make it clearer, here is a graph of what i wanna achieve:
Vector3.Distance(cubeA.position, ball.position) //will give a result of 6
Vector3.Distance(cubeB.position, ball.position) //will give a result of 4
Upvotes: 2
Views: 1964
Reputation: 4561
To have the exact evaluation distance you need you can consider to create the planes of your cube with the plane class. Then you can obtain the distance with Plane.ClosestPointOnPlane, that is the smalles distance in plane's normal direction, the distance that you need.
If you know the side of your cube, you can construct that plane directly, or get the face/plane of interest using the 6 planes of the cube if the rotation of them is random at the time the distance needs to be evaluated.
For the logic to get the face of interest Plane.GetSide to take into account specific cases where faces might be in conflict (corners of the cube)
Upvotes: 1
Reputation: 735
I understand what do you want. Ball is closer to CubeA because its right side closer to ball than cubeB's left side.
If you add rigidbodies and boxcolliders to cube and send ray from ball to cubes you can find short distance from ball.
For example I used line cast for this example.
Transform CubeB,CubeA,closest;
RaycastHit hit;
float dist;
if (Physics.Linecast(transform.position, CubeA.position,out hit))
{
dist= hit.distance;
closest=CubeA;
}
if (Physics.Linecast(transform.position, CubeB.position,out hit))
{
if(hit.distance>dist)
dist= hit.distance;
closest=CubeB;
}
Upvotes: 2