点到直线距离

发布时间 2023-11-02 23:24:21作者: yanghui01

直线方程的一般式:ax+by+c=0

点p(x1, y1)到直线的距离:

 

 

//点到直线的距离(一般式表示直线)
public static float PointToLineDistance(Vector2 point, float a, float b, float c)
{
    //直线一般式: ax+by+c=0
    //点到直线的距离公式: |ax+by+c|/sqrt(a^2+b^2)
    float dist = Mathf.Abs(a * point.x + b * point.y + c) / Mathf.Sqrt(a * a + b * b);
    return dist;
}

 

//点到直线的距离(两点表示直线)
public static float PointToLineDistance2(Vector2 point, Vector2 p1, Vector2 p2)
{
    float a = p2.y - p1.y;
    float b = p1.x - p2.x;
    float c = p1.y * p2.x - p1.x * p2.y;
    return PointToLineDistance(point, a, b, c);
}

//点到直线的距离(点斜式表示直线)
public static float PointToLineDistance3(Vector2 point, float k, float t)
{
    //直线点斜式: y=kx+t
    //任取直线上的两点
    float x1 = 0;
    float y1 = t;
    float x2 = 1;
    float y2 = k + t;

    float a = y2 - y1;
    float b = x1 - x2;
    float c = y1 * x2 - x1 * y2;
    return PointToLineDistance(point, a, b, c);
}

 

参考

判断线段与圆是否相交_判断线段和圆相交-CSDN博客