我必须计算从点到线的距离(检查它是线还是线段)。我不确定bool函数IsSegment是否正常工作。我可以提一些建议吗?谢谢。
double Distance_From_Line_to_Point(int *a, int *b, int *c, bool IsSegment) {
double distance;
int dot1;
int dot2;
distance = Cross_Product(a, b, c) / Distance(a, b);
if (IsSegment(a,b,c) == true) {
dot1 = Dot_Product(a, b, c);
if (dot1 > 0) {
return Distance(b, c);
}
dot2 = Dot_Product(b, a, c);
if (dot2 > 0) {
return Distance(a, c);
}
}
return fabs(distance);
}
bool IsSegment(int *a, int *b, int *c) {
double angle1;
double angle2;
angle1 = atan(double(b[1] - a[1]) / (b[0] - a[0]));
angle2 = atan(double(c[1] - b[1]) / (c[0] - b[0]));
if ((angle2 - angle1) * (180 / PI) > 90) {
return false;
}
return true;
}
答案 0 :(得分:4)
你不能只使用公式来获得距离吗?
所以找到这一行:
void getLine(double x1, double y1, double x2, double y2, double &a, double &b, double &c)
{
// (x- p1X) / (p2X - p1X) = (y - p1Y) / (p2Y - p1Y)
a = y1 - y2; // Note: this was incorrectly "y2 - y1" in the original answer
b = x2 - x1;
c = x1 * y2 - x2 * y1;
}
http://formule-matematica.tripod.com/distanta-de-dreapta.htm
double dist(double pct1X, double pct1Y, double pct2X, double pct2Y, double pct3X, double pct3Y)
{
double a, b, c;
getLine(pct2X, pct2Y, pct3X, pct3Y, a, b, c);
return abs(a * pct1X + b * pct1Y + c) / sqrt(a * a + b * b);
}
关于如何使用代码的示例:
#include <CMATH>
void getLine(double x1, double y1, double x2, double y2, double &a, double &b, double &c)
{
// (x- p1X) / (p2X - p1X) = (y - p1Y) / (p2Y - p1Y)
a = y1 - y2; // Note: this was incorrectly "y2 - y1" in the original answer
b = x2 - x1;
c = x1 * y2 - x2 * y1;
}
double dist(double pct1X, double pct1Y, double pct2X, double pct2Y, double pct3X, double pct3Y)
{
double a, b, c;
getLine(pct2X, pct2Y, pct3X, pct3Y, a, b, c);
return abs(a * pct1X + b * pct1Y + c) / sqrt(a * a + b * b);
}
int main(int argc, char* argv[])
{
double d = dist(1,2,3,4,5,6);
return 0;
}
答案 1 :(得分:1)
您需要2个公式:
行公式:来源this answer。
private Vector2 m_point1;
private Vector2 m_point1;
private float m_A;
private float m_B;
private float m_C;
public void CalculateLine()
{
m_A = m_point1.y - m_point2.y;
m_B = m_point2.x - m_point1.x;
m_C = m_point1.x * m_point2.y - m_point2.x * m_point1.y;
if(m_A == 0 && m_B == 0)
{
Debug.LogError("Line error: A & B = 0");
}
}
点到线的距离:来源Wikipedia
public float Distance2DPointToLine(Vector2 point)
{
return Mathf.Abs(m_A * point.x + m_B * point.y + m_C) /
Mathf.Sqrt(m_A * m_A + m_B * m_B);
}
这取决于您定义的“从点到线段的距离”
也许当您问到细分时,您可能没有想到结果,所以我无法为您回答细分部分。