Nearest point on a line
From Ogre Wiki
Ogre::Vector3 nearestPoint(Ogre::Vector3 pt1, Ogre::Vector3 pt2, Ogre::Vector3 testPoint)
{
// Find the point on a line defined by pt1 and pt2 that
// is nearest to a given point tp
// tp
// /|
// A / |
// / |
// / |
// pt1---o--------------pt2
// B' B
// Get the vectors between the points
Ogre::Vector3 A = testPoint - pt1;
Ogre::Vector3 B = pt2 - pt1;
// Find the cos of the angle between the vectors
float cosTheta = A.dotProduct(B) / (A.length() * B.length());
// Use that to calculate the length of B'
float BPrimeLength = A.length() * cosTheta;
// Find the ratio of the length of B' and B
float scale = BPrimeLength / B.length();
// Scale B by that ratio
B *= scale;
// Translate p1 by B, this puts it at o
Ogre::Vector3 C = pt1 + B;
return C;
}
A smaller and faster version:
Ogre::Vector3 nearestPoint(Ogre::Vector3 pt1, Ogre::Vector3 pt2, Ogre::Vector3 testPoint)
{
Ogre::Vector3 A = testPoint - pt1;
Ogre::Vector3 u = (pt2-pt1).normalisedCopy();
return pt1 + (A.dotProduct(u)) * u;
}

