ama*_*nda 16 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 = ???
}
Run Code Online (Sandbox Code Playgroud)
感谢您的回复,不是这不是家庭作业,只是一些黑客攻击我的正常专业领域.
这是下面建议的功能.它并不接近工作.如果我将圆的右上角90度部分每5度计算一次点作为起始点并调用下面的函数,圆的中心为x2,距离为4的y2则完全错误.它们位于中心的下方和右侧,长度与中心点一样长.有人有什么建议吗?
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) );
Run Code Online (Sandbox Code Playgroud)
}
我在stackoverflow上找到了这个解决方案,但是完全不了解它,任何人都可以澄清一下吗?
小智 34
我认为这属于MathOverflow,但我会回答,因为这是你的第一篇文章.首先计算从x1y1到x2y2的向量:
float vx = x2 - x1;
float vy = y2 - y1;
Run Code Online (Sandbox Code Playgroud)
然后计算长度:
float mag = sqrt(vx*vx + vy*vy);
Run Code Online (Sandbox Code Playgroud)
将向量标准化为单位长度:
vx /= mag;
vy /= mag;
Run Code Online (Sandbox Code Playgroud)
最后计算新的向量,即x2y2 + vxvy*(mag + distance).
*px = (int)((float)x1 + vx * (mag + distance));
*py = (int)((float)y1 + vy * (mag + distance));
Run Code Online (Sandbox Code Playgroud)
你可以省略一些与distance/mag相乘的计算.