Trip Back to Math Class

A recent project had me trying to find the distance between a point and a line segment, and a coworker reminded me that the distance from a point to the line can be found from the line perpendicular to the line, which passes through the point. That means figuring out the linear equation that defines the line segment. That’s y=mx+b, if you remember your Algebra days. I was stumped for a little while – stuck on the concept of solving for two variables with Actionscript. Actually, I was stuck on the concept of solving for a single variable in Actionscript, because I was being dumb.
Then, last weekend, laying in bed, I cracked it. Didn’t get around to writing the code until Monday. I wrote a LinearEquation class – capable of being given two points, a point and a slope (m), a point and a y-intercept (b), or a slope and a y-intercept – and builds a linear equation from it, in a manner of speaking – you can give it an x value, and it will return the y value. You can give it a y value, and it will give you the x. You can get the y-intercept, the slope, or the inverse of the slope – which will be the slope of a line perpendicular to that one.
Most importantly, the LinearEquation class has a static function – following the model of Point.distance() – LinearEquation.intersection(). It takes two LinearEquations as params, and returns the point where they intersect.
So we create a line and a point – then we get the inverse slope of the line, and pass that along with the point in to get another line. Then we get the intersection of the two, and voila, we’ve the line segment that is the distance from the point and the line.
Unless of course, that intersection is outside of the first line segment – that’s why LinearEquation gets extended by another class, LineSegment. But I’m not going to tell you all my secrets all at once.
So check out the demo I’ve set up. [ Line Segment / Linear Equation AS3 demo ]
And the practical applications for this? Not really sure yet, but there have to be quite a few. Just to name one or two, perhaps making line-segment checkpoints in a racing game, or part of an AI system where an enemy is shooting at you.
Maybe I’ll share the source sometime soon – if so, you can look for it here.