0

在此处输入图像描述

我有一个沿着向量(-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);
        }
4

1 回答 1

2

让我们根据您原始链接的内容再次执行公式。

  • 我们有一个线向量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)是我们随机值的正确距离,如果你可以在纸上画线和点,你可以测量距离,你会得到相同的值,使用标准尺。

于 2012-07-16T18:53:51.473 回答