2012-07-15 46 views
0

enter image description here载体 - >从矢量的垂直距离,以在2D空间中的点

我有沿着矢量(-0.7,-0.3)移动的子画面。我有另一点我的坐标 - 我们称它们为(xB | yB)。现在,相当一段时间以前,我学会了计算从矢量到点的垂直距离(本页上的第一个公式http://en.wikipedia.org/wiki/Perpendicular_distance)。但是我尝试过,如果我记录下来,它会返回一个令人难以置信的高值,这是100%错误。那么我做错了什么?看看我提供的图像。

incomingVector =(-0.7,-0.3) //这是子画面沿

bh.position移动矢量我想要计算到

这里的距离点是代码:

 // first I am working out the c Value in the formula in the link given above 
     CGPoint pointFromVector = CGPointMake(bh.incomingVector.x*theSprite.position.x,bh.incomingVector.y*theSprite.position.y); 
     float result = pointFromVector.x + pointFromVector.y; 
     float result2 = (-1)*result; 

     //now I use the formula 
     float test = (bh.incomingVector.x * bh.position.x + bh.incomingVector.y * bh.position.y + result2)/sqrt(pow(bh.incomingVector.x, 2)+pow(bh.incomingVector.y, 2)); 

     //the distance has to be positive, so I do the following 
     if(test < 0){ 
      test *= (-1); 
     } 
+0

对您定义矢量的图像为_V(-0.3; -0.7)_但在描述中您是在讨论_V(-0。7; -0.3)_。他们不一样。我试图找出为什么计算错误,你能给我一些结果吗?因为这个公式给我的随机值给出了很好的结果... – holex 2012-07-16 07:27:11

+0

是的,它并不重要,因为我已经假设矢量为(-0.3 | -0.7),而它确实是(-0.7 | -0.3) 。我在绘画中犯了一个错误。我得到的值是在600年代,而精灵的垂直距离显然只是大约100或更少(我的ipad屏幕上的近似估计值)。 – 2012-07-16 15:26:05

回答

2

让我们再次实现了公式,根据原稿link的内容。

  • 我们有一个矢量为线:V(A; B)
  • 我们对线(子画面的中心)一个P(X1,Y1 )
  • 我们另一点别的地方:B(XB,YB)

的测试这里是随机值的两行:

  1. a = -0.7; b = -0.3; x1 = 7; y1 = 7; xB = 5; yB = 5;
  2. a = -0.7; b = -0.3; x1 = 7; y1 = 7; xB = 5.5; yB = 4;

分子在以下则:(看来你是计算分子未知方式,我不明白你为什么这样做,因为这是计算连锁公式分子的正确方法,也许这就是你得到完全错误距离的原因。)

float _numerator = abs((b * xB) - (a * yB) - (b * x1) + (a * y1)); 
// for the 1. test values: (-0.3 * 5) - (-0.7 * 5) - (-0.3 * 7) + (-0.7 * 7) = -1.5 + 3.5 + 2.1 - 4.9 = -0.8 => abs(-0.8) = 0.8 
// for the 2. test values: (-0.3 * 5.5) - (-0.7 * 4) - (-0.3 * 7) + (-0.7 * 7) = -1.65 + 2.8 + 2.1 - 4.9 = -1.65 => abs(-1.65) = 1.65 

分母是以下则:

float _denomimator = sqrt((a * a) + (b * b)); 
// for the 1. test values: (-0.7 * -0.7) + (-0.3 * -0.3) = 0.49 + 0.09 = 0.58 => sort(0.58) = 0.76 
// for the 2. test values: (-0.7 * -0.7) + (-0.3 * -0.3) = 0.49 + 0.09 = 0.58 => sort(0.58) = 0.76 

的距离现在是很明显的:

float _distance = _numerator/_denominator; 
// for the 1. test values: 0.8/0.76 = 1.05 
// for the 2. test values: 1.65/0.76 = 2.17 

和这些结果(1.052.17)是正确的距离完全是为了我们的随机值,如果你可以在纸上绘制线条和点可以测量距离,你会得到相同的值,使用标准的标尺。

+0

非常感谢你!我非常拼命地尝试了几个小时才得到这个工作,现在我终于有了一个解决方案。我不能够感谢你:) – 2012-07-16 20:32:54

+0

没问题,你非常欢迎! :) – holex 2012-07-16 21:15:55