Circle line-segment collision detection algorithm?

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

    I wrote a small script to test intersection by projecting circle's center point on to line.

    vector distVector = centerPoint - projectedPoint;
    if(distVector.length() < circle.radius)
    {
        double distance = circle.radius - distVector.length();
        vector moveVector = distVector.normalize() * distance;
        circle.move(moveVector);
    }
    

    http://jsfiddle.net/ercang/ornh3594/1/

    If you need to check the collision with the segment, you also need to consider circle center's distance to start and end points.

    vector distVector = centerPoint - startPoint;
    if(distVector.length() < circle.radius)
    {
        double distance = circle.radius - distVector.length();
        vector moveVector = distVector.normalize() * distance;
        circle.move(moveVector);
    }
    

    https://jsfiddle.net/ercang/menp0991/

提交回复
热议问题