线相交功能

Line intersection function

我有一个直线交点函数(无限直线),其中两条直线都由两个点定义。

好像没有找到正确的交点,但是不知道哪里出错了。我按照维基百科上的数学解释创建了函数:

https://en.m.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line

这是我尝试从数学中构建函数:

//https://en.m.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line
//subscript 1 = a1
//subscript 2 = a2
//subscript 3 = b1
//subscript 4 = b2

    public static bool TryGetIntersectingPoint(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2, out Vector2 hitPoint)
    {
        hitPoint = Vector2.zero;

        // determinant
        float d = (a1.x-a2.x)*(b1.y-b2.y) - (a1.y-b2.y)*(b1.x-b2.x);

        // check if lines are parallel
        if (Approximately(d, epsilon)) return false;

        float px = (a1.x * a2.y - a1.y * a2.x) * (b1.x-b2.x) - (a1.x - a2.x) * (b1.x * b2.y - b1.y * b2.x);
        float py = (a1.x * a2.y - a1.y * a2.x) * (b1.y-b2.y) - (a1.y - a2.y) * (b1.x * b2.y - b1.y * b2.x);

        hitPoint = new Vector2(px,py) / d;
        return true;
    }

这是结果的视觉效果,您可以看到红点不在正确的交叉点位置。

我不确定哪里出了问题,希望有人知道如何解决这个问题?

这一行

float d = (a1.x-a2.x)*(b1.y-b2.y) - (a1.y-b2.y)*(b1.x-b2.x);

应该是

float d = (a1.x-a2.x)*(b1.y-b2.y) - (a1.y-a2.y)*(b1.x-b2.x);