在最接近另一个点的线段上获取点

Tom*_*mek 3 c++ math sfml

我想在线段AB上找到一个点,该点最接近另一个点P。

我的想法是:

  1. 使用A和B点坐标获取a1b1获取线型公式y1 = a1x + b1
  2. a1和P坐标获取法线公式y2 = a2x + b2
  3. 通过等式y1y2下一个使用上面的公式之一来获得交点x坐标,以得到y。

在此处输入图片说明

我的代码:

#include <SFML\Graphics.hpp>
#include <iostream>

sf::Vector2f getClosestPointOnLine(sf::Vector2f A, sf::Vector2f B, sf::Vector2f P)
{
    //convert to line formula
    float a = (B.y - A.y)/(B.x - A.x);
    float b = -a * A.x + A.y;

    //get normal line formula
    float a2 = -a / 2;
    float b2 = -a2 * P.x + P.y;

    //get x
    float a3 = a - a2;
    float b3 = b2 - b;

    float x = b3 / a3;

    //get y
    float y = a * x + b;

    return { x, y };
}

int main()
{
    sf::RenderWindow gameWindow(sf::VideoMode(800, 600), "App");

    sf::View view(sf::FloatRect(0, 0, 800, 600));
    gameWindow.setView(view);

    gameWindow.setFramerateLimit(60);

    sf::VertexArray plane(sf::LinesStrip, 2);

    plane[0] = { { view.getSize().x * 0.5f, view.getSize().y * 0.8f } };
    plane[1] = { { view.getSize().x * 0.8f, view.getSize().y * 0.6f } };

    sf::CircleShape ball(10);

    ball.setOrigin(10, 10);
    ball.setPosition({view.getSize().x * 0.7f, view.getSize().y * 0.4f});

    while (gameWindow.isOpen())
    {
        sf::Event e;
        while (gameWindow.pollEvent(e))
        {
            if (e.type == sf::Event::Closed)
            {
                gameWindow.close();
            }
        }

        //draw
        gameWindow.clear(sf::Color{30, 30, 30});

        ball.setPosition((sf::Vector2f)sf::Mouse::getPosition(gameWindow));

        sf::Vector2f closest = getClosestPointOnLine(plane[0].position, plane[1].position, ball.getPosition());

        sf::CircleShape cs(5);
        cs.setOrigin(5, 5 );
        cs.setPosition(closest);

        gameWindow.draw(cs);
        gameWindow.draw(plane);
        gameWindow.draw(ball);
        gameWindow.display();
    }
}
Run Code Online (Sandbox Code Playgroud)

结果: 在此处输入图片说明

如您所见,函数getClosestPointOnLine返回错误的交点。我的功能出了什么问题?

------------------编辑:如nm所述,-a / 2不是法线斜率的公式,我对这个公式有误,正确的是:-1 / a

Nic*_*ler 9

您想要的是P线段上的投影。您可以使用点积执行此操作:

auto AB = B - A;
auto AP = P - A;
float lengthSqrAB = AB.x * AB.x + AB.y * AB.y;
float t = (AP.x * AB.x + AP.y * AB.y) / lengthSqrAB;
Run Code Online (Sandbox Code Playgroud)

现在,tA和之间的插值参数B。如果是0,则该点投射到上A。如果是1,它将投影到B。分数值表示介于两者之间的点。如果要将投影限制在线段上,则需要钳位t

if(t < 0)
    t = 0;
if(t > 1)
    t = 1;
Run Code Online (Sandbox Code Playgroud)

最后,您可以计算出要点:

return A + t * AB;
Run Code Online (Sandbox Code Playgroud)