get closest point to a line

后端 未结 12 2008
逝去的感伤
逝去的感伤 2020-11-28 04:45

I\'d like to have a straight forward C# function to get a closest point (from a point P) to a line-segment, AB. An abstract function may look like this. I\'ve search through

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 04:52

    if anyone is interested in a C# XNA function based on the above:

        public static Vector2 GetClosestPointOnLineSegment(Vector2 A, Vector2 B, Vector2 P)
        {
            Vector2 AP = P - A;       //Vector from A to P   
            Vector2 AB = B - A;       //Vector from A to B  
    
            float magnitudeAB = AB.LengthSquared();     //Magnitude of AB vector (it's length squared)     
            float ABAPproduct = Vector2.Dot(AP, AB);    //The DOT product of a_to_p and a_to_b     
            float distance = ABAPproduct / magnitudeAB; //The normalized "distance" from a to your closest point  
    
            if (distance < 0)     //Check if P projection is over vectorAB     
            {
                return A;
    
            }
            else if (distance > 1)             {
                return B;
            }
            else
            {
                return A + AB * distance;
            }
        }
    

提交回复
热议问题