Sunday 27 January 2013

Shortest Distance Between a Point and a Line

Knowing if 2 objects are touching each other is only a part of collision detection. There are occasions when knowing how far each object is from each other is just as important.

Finding the shortest distance between 2 points is done with the Distance Formula. And the same goes for finding the distance between a point and a circle (you just need to check the distance between the point and the center and subtract the radius).
But the distance between a point and a line (or between other polygons defined with straight lines) is found through a different method.

We can draw an infinite number of lines starting from a single point, but only one of them is the shortest distance between that point and another line that doesn't pass through it (if it did the distance would be zero). That said line is the perpendicular!

The perpendicular line has a very interesting property. If the slope of the other line is m, then (in order to make the 90ยบ angle) the slope of the perpendicular is:

_   1  
     m




Knowing that all we need is to find the y-intercept (b) to finish the equation of the perpendicular line. And we can do that because we have the coordinates of point to replace the X and Y and reach the final value.
So starting from the line equation, the formula will be like this:

y = m x + b  <=>  b = y - m x



Once we have the equation for the perpendicular line determined, all we need to do is to find the intersection point between the 2 lines and calculate the distance between both points with the Distance Formula.

But there's an extra step we need to do if the other line is a line segment and not an infinite line. After finding the intersection point, we need to check if it's within the segment's boundaries, like shown here. If it's not then we just need to check the distance between the point and the line edges and see which one is the shortest.

Another thing we need to pay attention is if we're dealing with vertical or horizontal lines.
This is the only situation where the distance is being projected on a single axis, so the calculation is really straight-forward:

Vertical line:
distance = Lx - px
Horizontal line:
distance = Ly - py


0 comments:

Post a Comment

 

Break-a-Loop Copyright © 2013 | Template design by O Pregador | Powered by Blogger Templates