CSharp Get2DClosestPointToLineSegment

From scripting
Revision as of 05:06, 22 April 2017 by Nickpisca (talk | contribs) (Created page with " static double[] Get2DClosestPointToLineSegment(double[] A, double[] B, double[] OffPt, bool SkipExtremities) { double mAB = (B[1] - A[1]) / (B[0...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
        static double[] Get2DClosestPointToLineSegment(double[] A, double[] B, double[] OffPt, bool SkipExtremities)
        {
            double mAB = (B[1] - A[1]) / (B[0] - A[0]);
            double mCD = -1 * (B[0] - A[0]) / (B[1] - A[1]);

            double bAB = B[1] - (mAB * B[0]);
            double bCD = OffPt[1] - (mCD * OffPt[0]); 

            double fx = (bCD - bAB) / (mAB - mCD);
            double fy = (mAB * fx) + bAB;

            double[] D = {fx, fy, 0.0};
            double[] diff = ArraySubtraction(D, OffPt);   
            double DistMag = ArrayVectorMag(diff);

            double[] diffAB = ArraySubtraction(A, B);
            double[] diffAD = ArraySubtraction(D, A);
            double[] diffBD = ArraySubtraction(D, B);
            double magAB = ArrayVectorMag(diffAB);
            double magAD = ArrayVectorMag(diffAD);
            double magBD = ArrayVectorMag(diffBD);

            double[] winA = {0.0,0.0,0.0,0.0};
            if (magAB < (magAD + magBD - 0.00001))
            {
                if (SkipExtremities == true)
                {
                    winA[0] = 10000000.0; winA[1] = 10000000.0; winA[2] = 0.0; winA[3] = 10000000.0;
                }
                else
                {
                    if (magAD < magBD)
                    {
                        double[] diffAC = ArraySubtraction(A, OffPt);
                        double magAC = ArrayVectorMag(diffAC);
                        winA[0] = A[0]; winA[1] = A[1]; winA[2] = 0.0; winA[3] = magAC;
                    }
                    else
                    {
                        double[] diffBC = ArraySubtraction(B, OffPt);
                        double magBC = ArrayVectorMag(diffBC);
                        winA[0] = B[0]; winA[1] = B[1]; winA[2] = 0.0; winA[3] = magBC;
                    }
                }
            }
            else
            {
                winA[0] = fx; winA[1] = fy; winA[2] = 0.0; winA[3] = DistMag;
            }

            return winA;
        }


This subroutine was used in the development of the Mega-Dots World's Toughest Connect-the-Dots Puzzles.

Unrelated MEL scripting help located here: YSYT.