Calculate a points distance from a vector 3
Essentially, I have the following basic vector calculation:
var CamTrans = Camera.main.transform;
var endPos = CamTrans.position + (CamTrans.forward.normalized * renderDistanceInBlocks);
vector3 RenderLine = endPos - camTrans
I'm doing a procedural generation hobby-project, and I want to optimize my engine even further. I am trying to render objects from a grid of candidates based mainly on their proximity to the RenderLine. I googled and found some beastly math, but does Unity have a convenient way to calculate the distance of a point from a line so I can simply:
1) Get the above vector
2) Get the distance of every object from that vector (the step I am asking about)
3) draw only objects within x distance of this vector
4) draw the rest.
I can easily get three and four down, but two is tricky.
Thanks for reading this far, and if the answer is already here somewhere (I searched previous questions as well), please copy-past the link for an easy accepted answer.
Answer by ijidau · Nov 18, 2015 at 01:55 PM
That's for the distance between 2 points, not the distance between a point and a line.
It only takes 2 points as parameters, and that's not enough to define a point and a line.
To be fair, the question is asking for the distance between two vectors, even though that's not what OP means or wants.
Answer by Bonfire-Boy · Nov 18, 2015 at 02:16 PM
The first thing to note is that the Vector3 you have constructed, in RenderLine = camTrans - endPos
, does not actually represent the line joining those 2 points. The subtraction loses the positional information (that's the whole point of subtracting vectors like that). Think of it as "how to get from camTrans to endPos (without needing to know where camTrans is)". So your step 1) is not actually correct. You need to be using all the information (the coordinates of all 3 points) in your calculation.
Anyway, the formula you want can be found here: https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line (see under "Line defined by 2 points")
The maths isn't too beastly, IMO. You know your P0, P1 and (x0, y0), just plug in the values.
Or you could use the formula for d at the bottom of the Wolfram page you linked to. You just need to convert using "A x B" becomes Vector3.Cross(A, B)
and "|A|" becomes A.magnitude
Your answer
Follow this Question
Related Questions
Vector3.Distance returning weird distances? 1 Answer
InverseTransformPoint() help 0 Answers
Things that I don't get in Procedural Cave generation Tutorial 1 Answer
vector3 distance same script different objects 0 Answers
Dot Product not equals 1 0 Answers