[英]Point on a straight line specific distance away in C
如何在直线上找到距给定点特定距离的点。 我正在用C编写此代码,但没有得到正确的答案。任何人都可以指导我做错什么。
我得到了x1,y1,x2,y2的值,并且距离还不错。 使用这些我可以发现斜率m和y截距也很好。 现在,我需要在连接这两个点的直线上找到距点x1,y1 10个单位的点。 我似乎在这里错了。 这是我编写的代码。
int x1 = node[n].currentCoordinates.xCoordinate;
int y1 = node[n].currentCoordinates.yCoordinate;
int x2 = node[n].destinationLocationCoordinates.xCoordinate;
int y2 = node[n].destinationLocationCoordinates.yCoordinate;
int distanceleft = (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1);
distanceleft = sqrt(distanceleft);
printf("Distance left to cover is %d\n",distanceleft);
int m = (y2 - y1)/(x2 - x1); // slope.
int b = y1 - m * x1; //y-intercept
//find point on the line that is 10 units away from
//current coordinates on equation y = mx + b.
if(x2 > x1)
{
printf("x2 is greater than x1\n");
int tempx = 0;
int tempy = 0;
for(tempx = x1; tempx <= x2; tempx++)
{
tempy = y1 + (y2 - y1) * (tempx - x1)/(x2 - x1);
printf("tempx = %d, tempy = %d\n",tempx,tempy);
int distanceofthispoint = (tempy - y1) * (tempy - y1) + (tempx - x1) * (tempx - x1);
distanceofthispoint = sqrt((int)distanceofthispoint);
if(distanceofthispoint >= 10)
{
//found new points.
node[n].currentCoordinates.xCoordinate = tempx;
node[n].currentCoordinates.yCoordinate = tempy;
node[n].TimeAtCurrentCoordinate = clock;
printf("Found the point at the matching distance\n");
break;
}
}
}
else
{
printf("x2 is lesser than x1\n");
int tempx = 0;
int tempy = 0;
for(tempx = x1; tempx >= x2; tempx--)
{
tempy = y1 + (y2 - y1) * (tempx - x1)/(x2 - x1);
printf("tempx = %d, tempy = %d\n",tempx,tempy);
int distanceofthispoint = (tempy - y1) * (tempy - y1) + (tempx - x1) * (tempx - x1);
distanceofthispoint = sqrt((int)distanceofthispoint);
if(distanceofthispoint >= 10)
{
//found new points.
node[n].currentCoordinates.xCoordinate = tempx;
node[n].currentCoordinates.yCoordinate = tempy;
node[n].TimeAtCurrentCoordinate = clock;
printf("Found the point at the matching distance\n");
break;
}
}
}
printf("at time %f, (%d,%d) are the coordinates of node %d\n",clock,node[n].currentCoordinates.xCoordinate,node[n].currentCoordinates.yCoordinate,n);
这是数学上的样子,我没有时间用C编写东西。
您有一个点(x1,y1)
和另一个点(x2,y2)
,链接时会给您一个分段。
因此,您具有方向矢量v=(xv, yv)
,其中xv=x2-x1
和yv=y2-y1
。
现在,您需要将该向量除以其范数,得到一个新向量: vector = v / sqrt(xv 2 + yv 2 ) 。
现在,您只需将向量乘以所需点的距离即可:
位置=(x原点,y原点)+距离×向量
我希望这有帮助!
或更简单
从斜坡上找到角度
θ = arctan(y2-y1/x2-x1)
您可能需要根据斜率的分子和分母来修改θ的象限。 然后您可以找到与(x1,y1)的距离d的直线上的任何点
x_new = x1 + d×cos(θ)
y_new = y1 + d×sin(θ)
在这种情况下,您的d = 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.