Circle line-segment collision detection algorithm?

前端 未结 28 1338
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:38

I have a line from A to B and a circle positioned at C with the radius R.

\"Image\"

What is a good alg

28条回答
  •  无人及你
    2020-11-22 07:02

    This Java Function returns a DVec2 Object. It takes a DVec2 for the center of the circle, the radius of the circle, and a Line.

    public static DVec2 CircLine(DVec2 C, double r, Line line)
    {
        DVec2 A = line.p1;
        DVec2 B = line.p2;
        DVec2 P;
        DVec2 AC = new DVec2( C );
        AC.sub(A);
        DVec2 AB = new DVec2( B );
        AB.sub(A);
        double ab2 = AB.dot(AB);
        double acab = AC.dot(AB);
        double t = acab / ab2;
    
        if (t < 0.0) 
            t = 0.0;
        else if (t > 1.0) 
            t = 1.0;
    
        //P = A + t * AB;
        P = new DVec2( AB );
        P.mul( t );
        P.add( A );
    
        DVec2 H = new DVec2( P );
        H.sub( C );
        double h2 = H.dot(H);
        double r2 = r * r;
    
        if(h2 > r2) 
            return null;
        else
            return P;
    }
    

提交回复
热议问题