1
\$\begingroup\$

I have a line in 3D defined by point P0 and direction vector D. For given input point P on a line defined as above, I want to test if P is in front of point P0. The code will be used in GLSL fragment shader.

So far, my best solution is following GLSL function:

bool IsInFront(vec3 P, vec3 P0, vec3 D)
{
  float d = length(P - P0);
  vec3 Pp = P0 + d * D;
  return (length(Pp - P) < 1.0E-4);
}

Explanation is simple. d is distance between P and P0, and there are only two possible positions on a line where a point with distance d from point P0 can be on a line: in front, or behind point P0. Then I just check if positive point is same as input P.

However, this code uses precision 1.0E-4, and recalculation of input point P. Is there a faster and numerically more stable way to do this?

Regards

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

I think I found an answer by myself.

bool IsInFront(vec3 P, vec3 P0, vec3 D)
{
  vec3 D2 = P - P0;
  float c = dot(D, D2);
  return (c > 0.0);
}

In this solution, D2 is unnormalized vector from P0 to P which is either in same or opposite direction compared to D. c is cosine similarity between D and D2 multiplied by length of vector D2. It is either length of vector D2, or negated length of vector D2 depending on it's orientation.

\$\endgroup\$
0
\$\begingroup\$

Not sure if its relevant (Not 100% sure what your actually asking, but ill attempt my advice anyway) but use a raycast, this will then have a function that allows you to measure the "ray's" distance between the player and an object, or 2 objects if you prefer.

\$\endgroup\$

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.