hoopla
hoopla

Reputation: 1

Find the closest point on a ray from another point

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.

Upvotes: 0

Views: 1559

Answers (2)

Pierre Baret
Pierre Baret

Reputation: 1893

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

enter image description here

Upvotes: 2

Jesús Jangwon Kim
Jesús Jangwon Kim

Reputation: 126

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

Upvotes: 3

Related Questions