# Most Efficient Way to Check Player Distance from a Line?

I need to get the player's distance from a line (or the outside edges of an Gameobject, if that's easier) throughout their time in the game. I need the code to be fairly simple because I'm a novice (though if it's thoroughly explained, I can implement more complex solutions).

Is there an optimal way to do this that doesn't involve resorting to using the full formula for a point to a line? Because I think I might have some trouble implementing that in unity's system (translating to/from coordinate systems, maybe).

Thanks!

• gameObject.transform.position it gives GameObjects's location in 3D space, now calculate according to your formula – Maifee Ul Asad May 15 '19 at 5:45
• There is a direct formula, what kind of optimization you are talking about ? – Maifee Ul Asad May 15 '19 at 5:47
• I have several lines, each of which are made up of a number of game objects (because some need to be visible at different times). I need to find the closest line to the player at each time point throughout the game. – Pete Bloom May 15 '19 at 10:30
• "I think I might have some trouble implementing that in unity's system" How about trying it first, using the basic formula you can find with a Google search. It will probably work just fine for your needs — it's a very cheap calculation by game standards. If you encounter a problem, edit your question to detail exactly how you implemented it and what specific problem you found, then we can help you solve that problem. – DMGregory May 15 '19 at 13:04
• @MaifeeUlAsad for example, compare squares instead of distances, to avoid expensive square root calculations (if he wants to find minimum or maximum distance). – trollingchar May 15 '19 at 14:05

First of all, because I don't have a compiler right now:

List<GameObject[]> gList=new List<>();//this may have some problem, try initiating in your way

GameObject[] line1=new GameObject{g1,g2,g3}; //g-n is just some gameobject
GameObject[] line2=new GameObject{g4,g5,g6,g7};

GameObject[] targeted=null;

foreach(GameObject[] x in gList)
{
Vector3 f=x[0].transform.position;
Vector3 l=x[x.Length-1].transform.position;

//calculate distance as you know the math
//if(condition) //depending upon min or max or what-ever
//targeted=x;

}


Maybe this will help

• Please explain what the code does, it doesn't help that much this way – Bálint May 15 '19 at 13:39