5

我必须计算点到线的距离(检查它是线还是线段)。我不确定布尔函数 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;
}
4

2 回答 2

6

你不能用公式来得到距离吗?

所以要找到这条线:

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;
}
于 2012-08-26T18:23:53.963 回答
3

点到线的距离

点到线的距离

你需要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");
        }
    }

点到线的距离:来源维基百科

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);
}

点到线段的距离

这取决于您定义的“从点到线段的距离”

也许从点到线段的距离是从点到线段中点的距离: 到中点?

如果点可以投影到线段上,可能距离可用 距离:存在或不存在

可能你在问segment的时候没有想象到结果是什么,所以我无法为你回答segment部分。

于 2018-10-16T04:46:32.517 回答