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

2021-12-21 00:00:00 math c graphics vector c++

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

Looking for the quickest way to calculate a point that lies on a line a given distance away from the end point of the line:

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 = ???
}  

感谢您的回复,不,这不是作业,只是一些黑客攻击我通常的专业领域.

Thanks for the responses, no this is not homework, just some hacking out of my normal area of expertise.

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

This is the function suggested below. It's not close to working. If I calculate points every 5 degrees on the upper right 90 degree portion of a circle as starting points and call the function below with the center of the circle as x2,y2 with a distance of 4 the end points are totally wrong. They lie below and to the right of the center and the length is as long as the center point. Anyone have any suggestions?

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但不完全理解,谁能解释一下?

I've found this solution on stackoverflow but don't understand it completely, can anyone clarify?

推荐答案

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

I think this belongs on MathOverflow, but I'll answer since this is your first post. First you calculate the vector from x1y1 to x2y2:

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

然后计算长度:

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

将向量归一化为单位长度:

Normalize the vector to unit length:

vx /= mag;
vy /= mag;

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

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

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

您可以省略一些乘以距离/mag 的计算.

You can omit some of the calculations multiplying with distance / mag instead.

相关文章