0
\$\begingroup\$

quick diagram to explain what i mean. i have a start and an end, the third point can be anywhere in space, but i need to calculate from 0-1 how far they are in-between these two points.

The points are 3d but im only using two axes if that matters.

The answer to this is probably pretty simple but i cant think of it and i cant find the right search terms to find anything that helps me.

example

\$\endgroup\$
1
\$\begingroup\$

The point projected onto the Start-End segment can be found using the dot product operator to perform a scalar projection:

enter image description here

In your scenario, let's call \$P\$ the Point, \$S\$ the Start, and \$E\$ the End points. If \$P'\$ is the projection of \$P\$ onto the segment \$\overline{SE}\$, its length is:

$$ \overline{SP'} = \overline{SP} \space cos \theta = \mathbf{p} \cdot \mathbf{l} = \mathbf{p'} $$

where \$\theta\$ is the angle between the vector \$\mathbf{p}\$ (pointing from \$S\$ towards \$P\$) and the vector \$\mathbf{l}\$ (pointing from \$S\$ towards \$E\$, thus the segment itself).

Depending on the implementation, you need some additional math first to find out the length of those vectors before performing dot product on them, which in Unity's C# is something like:

float projP = Vector3.Dot(P-S, E-S);

Finally, you can compute the 0-1 value of where \$P'\$ lies when between \$P\$ and \$E\$, by normalising the length of \$\mathbf{p'}\$ over \$\mathbf{l}\$:

$$ \hat{\mathbf v}=\frac{\mathbf p'}{\|\mathbf l\|} $$

Or:

float percentage = projP / (E-S).magnitude;
\$\endgroup\$
0

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.