Circle line-segment collision detection algorithm?

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

    Just an addition to this thread... Below is a version of the code posted by pahlevan, but for C#/XNA and tidied up a little:

        /// 
        /// Intersects a line and a circle.
        /// 
        /// the location of the circle
        /// the radius of the circle
        /// the starting point of the line
        /// the ending point of the line
        /// true if the line and circle intersect each other
        public static bool IntersectLineCircle(Vector2 location, float radius, Vector2 lineFrom, Vector2 lineTo)
        {
            float ab2, acab, h2;
            Vector2 ac = location - lineFrom;
            Vector2 ab = lineTo - lineFrom;
            Vector2.Dot(ref ab, ref ab, out ab2);
            Vector2.Dot(ref ac, ref ab, out acab);
            float t = acab / ab2;
    
            if (t < 0)
                t = 0;
            else if (t > 1)
                t = 1;
    
            Vector2 h = ((ab * t) + lineFrom) - location;
            Vector2.Dot(ref h, ref h, out h2);
    
            return (h2 <= (radius * radius));
        }
    

提交回复
热议问题