Circle - Line Intersection not working properly?

2019-02-20 04:46发布

问题:

I wrote this circle-line intersection detection after http://mathworld.wolfram.com/Circle-LineIntersection.html, but it appears like it or I am missing something.

    public static bool Intersect
    (Vector2f CirclePos, float CircleRad, Vector2f Point1, Vector2f Point2)
    {
        Vector2f p1 = Vector2f.MemCpy(Point1);
        Vector2f p2 = Vector2f.MemCpy(Point2);

        // Normalize points
        p1.X -= CirclePos.X;
        p1.Y -= CirclePos.Y;
        p2.X -= CirclePos.X;
        p2.Y -= CirclePos.Y;

        float dx = p2.X - p1.X;
        float dy = p2.Y - p1.Y;
        float dr = (float)Math.Sqrt((double)(dx * dx) + (double)(dy * dy));
        float D = p1.X * p2.Y * p2.X - p1.Y;

        float di = (CircleRad * CircleRad) * (dr * dr) - (D * D);

        if (di < 0) return false;
        else return true;
    }

The only occasion it returns true is when Point2 is withing the circle. What am I doing wrong?

回答1:

float D = p1.X * p2.Y * p2.X - p1.Y;

You've mixed up your operators on this line.