By
Jeff Lander
Gamasutra
February 10, 2000
This
article originally appeared in the
January 1999 issue of:

|
|
Features

Listing
3. Finding the Nearest
Point on a Line Segment.
// Procedure: GetNearestPoint
// Purpose: Find
the nearest point on a line segment
// Arguments: Two
endpoints to a line segment a and b,
// and
a test point c
// Returns: Sets
the nearest point on the segment in nearest
void CFateView::GetNearestPoint(tPoint2D
*a, tPoint2D *b,tPoint2D *c,tPoint2D *nearest)
{
/// Local Variables
///////////////////////
long
dot_ta,dot_tb;
//
SEE IF a IS THE NEAREST POINT - ANGLE IS OBTUSE
dot_ta
= (c->x - a->x)*(b->x - a->x) + (c->y - a->y)*(b->y
- a->y);
if
(dot_ta <= 0) // IT IS OFF THE AVERTEX
{
nearest->x
= a->x;
nearest->y
= a->y;
return;
}
dot_tb
= (c->x - b->x)*(a->x - b->x) + (c->y - b->y)*(a->y
- b->y);
//
SEE IF b IS THE NEAREST POINT - ANGLE IS OBTUSE
if
(dot_tb <= 0)
{
nearest->x
= b->x;
nearest->y
= b->y;
return;
}
//
FIND THE REAL NEAREST POINT ON THE LINE SEGMENT - BASED
ON RATIO
nearest->x
= a->x + ((b->x - a->x) * dot_ta)/(dot_ta + dot_tb);
nearest->y
= a->y + ((b->y - a->y) * dot_ta)/(dot_ta + dot_tb);
}
Back
to Article
|