instructions

The closest point to the line is the vertical foot. But the closest coordinates from the point to the ray are not necessarily perpendicular feet, depending on where the point is.

The geometric

A ray consists of a point and a vector, which, with other points, naturally forms a plane. Therefore, the point in three dimensions to the nearest point of the ray can be directly translated into two dimensions.

In the figure below, when point C is in the positive direction of ray AB, the closest point from point C to the ray is actually the closest point on the line between point C and ray AB:

If D and E are in the negative direction of ray AB, then the nearest point should be the origin of ray A:

So how do you determine whether the point is in the positive or negative direction? We can use the dot product. Construct A vector from A to D, dot it with the ray vector AB. When the dot product is greater than 0, it is in the positive direction; If it’s less than 0, it’s in the negative direction.

code

// define the ray structure
struct Ray {
    let position:simd_float3
    let direction:simd_float3
}


// The nearest point from point to ray
static func nearestPointOnRay(from point:simd_float3, to ray:Ray) -> simd_float3 {
    let vector = point - ray.position
    let normalizedDirection = normalize(ray.direction)
    let dotValue = dot(vector, normalizedDirection)
    if dotValue < = 0 {
        return ray.position
    }
    let tarPoint = ray.position + dotValue * normalizedDirection
    return tarPoint
}
Copy the code

Project code

This series code has been published in making: ComputationalGeometrySwift