给定起点和终点以及距离,计算沿线的点

时间:2009-11-25 21:38:11

标签: c++ c math graphics vector

寻找计算线上点的最快方法 距离线的终点一定距离:

void calculate_line_point(int x1, int y1, int x2, int y2, int distance, int *px, int *py) 
{
    //calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2
    *px = ???
    *py = ???
}  

感谢您的回复,不是这不是功课,只是一些黑客攻击 我的正常专业领域。

这是下面建议的功能。它并不接近工作。如果我 在右上角90度部分每5度计算一次点数 一个圆作为起点并调用下面的函数,圆的中心为x2,y2的距离为4,端点完全错误。它们位于中心的下方和右侧,长度与中心点一样长。有人有什么建议吗?

void calculate_line_point(int x1, int y1, int x2, int y2, int distance)
{

//calculate a point on the line x1-y1 to x2-y2 that is distance from x2-y2

  double vx = x2 - x1; // x vector
  double vy = y2 - y1; // y vector

  double mag = sqrt(vx*vx + vy*vy); // length

  vx /= mag;
  vy /= mag;

// calculate the new vector, which is x2y2 + vxvy * (mag + distance).

  px = (int) ( (double) x2 + vx * (mag + (double)distance) );
  py = (int) ( (double) y2 + vy * (mag + (double)distance) );

}

我在stackoverflow上找到了this解决方案但是没有完全理解,有人可以澄清吗?

2 个答案:

答案 0 :(得分:34)

我认为这属于MathOverflow,但我会回答,因为这是你的第一篇文章。 首先计算从x1y1到x2y2的矢量:

float vx = x2 - x1;
float vy = y2 - y1;

然后计算长度:

float mag = sqrt(vx*vx + vy*vy);

将向量标准化为单位长度:

vx /= mag;
vy /= mag;

最后计算新的向量,即x2y2 + vxvy *(mag + distance)。

*px = (int)((float)x1 + vx * (mag + distance));
*py = (int)((float)y1 + vy * (mag + distance));

您可以省略一些与distance / mag相乘的计算。

答案 1 :(得分:1)

这些方程式错误:

px = (int) ( (double) x2 + vx * (mag + (double)distance) );

py = (int) ( (double) y2 + vy * (mag + (double)distance) );

正确的公式为:

px = (int) ( (double) x2 + vx * (double)distance );

py = (int) ( (double) y2 + vy * (double)distance );

汤姆

相关问题