我想在线段AB上找到离另一个点P最近的点。
我的想法是:
- 从A和B点坐标中获取线段公式y1 = a1x + b1的a1和b1。
- 从a1和P坐标中获取垂线的公式y2 = a2x + b2。
- 通过等式y1和y2来得到交点的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();
}
}
结果:
![enter image description here](https://istack.dev59.com/bj4j2.webp)
getClosestPointOnLine
返回的交点是错误的。我的函数有什么问题吗?------------------编辑: 正如n.m.所提到的,
-a / 2
不是法线斜率公式,我关于这个公式错了,正确的公式是:-1 / a
。