2012-04-11 95 views
0

如何找到与给定点相距特定距离的直线上的点。我正在用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); 

回答

7

这里是如何在数学,我没有时间写东西C.

你有一个点(x1,y1)和另外一个(x2,y2),当链接它给你一个部分。

因此,您有一个定向矢量v=(xv, yv)其中xv=x2-x1yv=y2-y1

现在,你需要它的标准来划分这个载体,你会得到一个新的向量:矢量= V/SQRT(十五 + YV )。现在

,你只需要添加到您的原点乘以距离矢量上,你想你的观点:

位置=(x原点,y原点)+距离×矢量

我希望这有助于!

+0

同意。我不认为你真的需要在这里循环。这是代数,而不是算法。 – FlavorScape 2012-04-11 22:19:38

+0

向量方程中的最后一个'v'是否应该在sqrt下或分数下或分数外?你忘了关闭支架:) – 2012-10-09 12:00:12

+0

哦,好的,没关系。我明白。它在外面,你只是乘以1/..而不是v/... – 2012-10-09 12:45:52

0

或者更简单,

从坡上

θ = arctan(y2-y1/x2-x1) 

您可能需要修改θ的基础上斜坡的分子和分母的象限查找的角度。然后,你可以找到从(X1,Y1)

x_new = x1 + d×cos(θ) 
y_new = y1 + d×sin(θ) 

在距离d线路上的任何点。在这种情况下,有d = 10

相关问题