给定起点和终点以及距离,计算沿线的点
寻找最快的方法来计算位于距离线的终点给定距离的线上的点:
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 = ??? }
感谢您的回复,不是这不是家庭作业,只是一些黑客攻击我的正常专业领域。
这是下面建议的function。 它并不接近工作。 如果我在圆的右上角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上找到了这个解决方案,但是完全不了解它,有人可以澄清吗?
我认为这属于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相乘的计算。
这些方程是错误的:
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 );
汤姆