我正在计算一条线的距离。但我的距离越来越远。以下是我的代码,它与线路相距很远。
float px,py,something,u;
px=x2-x1;
py=y2-y1;
something = px*px + py*py;
u = ((x - x1) * px + (y - y1) * py) /(something);
if( u > 1)
{
u = 1;
// MinDist=0;
}
else if (u < 0)
{
u = 0;
//MinDist=0;
}
float xx = x1 + u * px;
float yy = y1 + u * py;
float dx = xx - x;
float dy = yy - y;
float dist= (float)Math.sqrt((double)dx*dx +(double) dy*dy);
Dist给出了错误的答案。
答案 0 :(得分:2)
来自:http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Vector_formulation
distance(x=a+tn, p) = ||(a-p)-((a-p).n)n||
其中:
a = (x1, y1) //First point on line
n = |(x2-x1, y2-y1)| //Normalised direction vector
p = (x, y) //Query point
所以,不要全部做,而是制作函数并提供有意义的名称,以帮助您遵循公式:
float[] a = new float[]{x1, y1};
float[] n = new float[]{x2-x1, y2-y1};
normalize(n);
float[] p = new float[]{x, y};
float[] aMinusP = subtract(a, p);
float aMinusPDotn = dot(aMinusP, n);
// vec2a.vec2b
float dot(float[] vec2a, float[] vec2b)
{
return vec2a[0]*vec2b[0] + vec2a[1]*vec2b[1];
}
// ||vec2||
float len(float[] vec2)
{
return (float)Math.Sqrt(dot(vec2, vec2));
}
// vec2/||vec2||
void normalize(float[] vec2)
{
float length = len(vec2);
vec2[0] /= length;
vec2[1] /= length;
}
// vec2a - vec2b
float[] subtract(float[] vec2a, float[] vec2b)
{
return new float[]{vec2a[0]-vec2b[0],vec2a[1]-vec2b[1]};
}