How to find a point in a triangle closest to a point in space. The Dot-product is your friend. We're going to use it three times to find the distance from our triangle to the origin and then to find the distance from the point in space to the triangle. Using that distance value, we can trivially calculate the point in the triangle closest to the point in space.
There are no assumptions needed since all calculations are performed internally. You do need a 3D Vector class that has a Dot method.
Vector GetPointInTriangleClosestToPointInSpace (const Vector& pointInSpace,
const Vector& pointInTriangle,
const Vector& normalOfTriangle)
{
// Calculate D. This is defined in most calculus books and is the
// scaler 'distance from the triangle to the origin'
float D = pointInTriangle.Dot (normalOfTriangle);
// this is your standard projection equation defined in
// precalculus and is the minimum distance from the point
// in space to our triangle. We subtract the D value to 'normalize'
// the length. projectionLength could also be called distance.
float projectionLength = (normalOfTriangle.Dot (pointInSpace) - D) / (normalOfTriangle.Dot (normalOfTriangle));
// our final calculation is to take the point in space and once
// we subtract the minimum distance from it to the triangle, we
// have the new position of the point in the triangle
// closest to our point in space.
return pointInSpace - projectionLength*normalOfTriangle;
}
No comments:
Post a Comment