0

我正在计算点到一条线的距离。但我走错了距离。以下是我的一段代码,它离线越来越远。

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 给出了错误的答案。

4

1 回答 1

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]};
}
于 2013-09-04T06:46:55.673 回答