Circle line-segment collision detection algorithm?

前端 未结 28 2048
被撕碎了的回忆
被撕碎了的回忆 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:15

    I just needed that, so I came up with this solution. The language is maxscript, but it should be easily translated to any other language. sideA, sideB and CircleRadius are scalars, the rest of the variables are points as [x,y,z]. I'm assuming z=0 to solve on the plane XY

    fn projectPoint p1 p2 p3 = --project  p1 perpendicular to the line p2-p3
    (
        local v= normalize (p3-p2)
        local p= (p1-p2)
        p2+((dot v p)*v)
    )
    fn findIntersectionLineCircle CircleCenter CircleRadius LineP1 LineP2=
    (
        pp=projectPoint CircleCenter LineP1 LineP2
        sideA=distance pp CircleCenter
        --use pythagoras to solve the third side
        sideB=sqrt(CircleRadius^2-sideA^2) -- this will return NaN if they don't intersect
        IntersectV=normalize (pp-CircleCenter)
        perpV=[IntersectV.y,-IntersectV.x,IntersectV.z]
        --project the point to both sides to find the solutions
        solution1=pp+(sideB*perpV)
        solution2=pp-(sideB*perpV)
        return #(solution1,solution2)
    )
    

提交回复
热议问题