【发布时间】:2009-11-25 21:38:11
【问题描述】:
寻找计算直线上点的最快方法 距离线的终点给定的距离:
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 解决方案,但不完全理解,谁能澄清一下?
【问题讨论】:
-
也许你应该使用浮点数/双精度数,因为你会得到舍入错误。这可能是一个问题。
-
卢卡斯说了什么。另外,您可能在我有错字时阅读了我的帖子。如果 x1y1 是原点,您需要 x1y1 + vxvy * (mag + distance),而不是 x2y2。也就是说,从原点开始,您要使用从 x1y1 到 x2y2 的方向,行进 到 x2y2 的距离加上额外的距离。尽管我认为您可能想改写您的问题。你到底想做什么?现在的问题似乎更像是一个中间问题。
标签: c++ c math graphics vector