The simplest way to represent a line is using a linear equation, like this
y = mx + c
It also has a more subtle problem; like the inverse trigonometric functions it becomes less accurate as it approaches certain limits. For example as a line becomes increasingly vertical and m approaches infinity small errors in x are amplified when calculating y. The errors are amplified the other way for nearly horizontal lines.
A better way is to supply a point on the line and a vector along it. The vector can be normalised as it's only its direction that's important. The advantage of vectors (formally Euclidian vectors) is that they are independent of the coordinate system, so don't have the same problems of failing in certain directions.
Alternately just two points on the line can be given. This is the approach used last week, as it makes the function especially straightforward. It's worth giving this function again to illustrate it.
function hitLine(x1:Number, y1:Number,
x2:Number, y2:Number):Boolean {
// calculate the unit vector along the line
var dX:Number = x1 - x2;
var dY:Number = y1 - y2;
var len:Number = Math.sqrt(dX * dX + dY * dY);
var recip:Number = 1 / len;
dX *= recip;
dY *= recip;
// perp dot product:
return Math.abs((fX - x1) * dY - (fY - y1) * dx) < fR;
}
No comments:
Post a Comment