Circle line-segment collision detection algorithm?

前端 未结 28 1985
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:59

    I would use the algorithm to compute the distance between a point (circle center) and a line (line AB). This can then be used to determine the intersection points of the line with the circle.

    Let say we have the points A, B, C. Ax and Ay are the x and y components of the A points. Same for B and C. The scalar R is the circle radius.

    This algorithm requires that A, B and C are distinct points and that R is not 0.

    Here is the algorithm

    // compute the euclidean distance between A and B
    LAB = sqrt( (Bx-Ax)²+(By-Ay)² )
    
    // compute the direction vector D from A to B
    Dx = (Bx-Ax)/LAB
    Dy = (By-Ay)/LAB
    
    // the equation of the line AB is x = Dx*t + Ax, y = Dy*t + Ay with 0 <= t <= LAB.
    
    // compute the distance between the points A and E, where
    // E is the point of AB closest the circle center (Cx, Cy)
    t = Dx*(Cx-Ax) + Dy*(Cy-Ay)    
    
    // compute the coordinates of the point E
    Ex = t*Dx+Ax
    Ey = t*Dy+Ay
    
    // compute the euclidean distance between E and C
    LEC = sqrt((Ex-Cx)²+(Ey-Cy)²)
    
    // test if the line intersects the circle
    if( LEC < R )
    {
        // compute distance from t to circle intersection point
        dt = sqrt( R² - LEC²)
    
        // compute first intersection point
        Fx = (t-dt)*Dx + Ax
        Fy = (t-dt)*Dy + Ay
    
        // compute second intersection point
        Gx = (t+dt)*Dx + Ax
        Gy = (t+dt)*Dy + Ay
    }
    
    // else test if the line is tangent to circle
    else if( LEC == R )
        // tangent point to circle is E
    
    else
        // line doesn't touch circle
    

提交回复
热议问题