Home > front end >  Find the closest point on a ray from another point
Find the closest point on a ray from another point

Time:08-24

I'm currently in the process of making a 3D engine and for lighting one of the things I have to do is cast a 3d ray and the find the point on that ray that is closest to another given point. My question is does anyone know of an efficient way of doing that within code?

To be more specific I am casting a ray with a specific origin p and a direction d in a 3D world and given another 3d point c I would like to find the point on that ray that is closest to c.

CodePudding user response:

Assuming you are familiar with vectors (as in Linear Algebra)

// Here, Vector is a vector in Rn, not a dynamic array.
Vector v = c - p;
float dotProd = dot(v, d);
dotProd = max(dotProd, 0.0f); // if dotProd is negative, the closest point is in the opposite direction to d.
Vector e = p   d * dotProd;

Now, e is the closest point to c on the ray

CodePudding user response:

an image is worth thousand words, so an image a few words with maths formulas is worth thousand few words.

enter image description here

  • Related