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).


  • \$\begingroup\$ gameObject.transform.position it gives GameObjects's location in 3D space, now calculate according to your formula \$\endgroup\$ – Maifee Ul Asad May 15 '19 at 5:45
  • 1
    \$\begingroup\$ There is a direct formula, what kind of optimization you are talking about ? \$\endgroup\$ – Maifee Ul Asad May 15 '19 at 5:47
  • \$\begingroup\$ 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. \$\endgroup\$ – Pete Bloom May 15 '19 at 10:30
  • \$\begingroup\$ "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. \$\endgroup\$ – DMGregory May 15 '19 at 13:04
  • \$\begingroup\$ @MaifeeUlAsad for example, compare squares instead of distances, to avoid expensive square root calculations (if he wants to find minimum or maximum distance). \$\endgroup\$ – 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


Maybe this will help

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.