Search code examples
algorithmlanguage-agnosticgeometry

Best way to find a point on a circle closest to a given point


Given a point (pX, pY) and a circle with a known center (cX,cY) and radius (r), what is the shortest amount of code you can come up with to find the point on the circle closest to (pX, pY) ?

I've got some code kind of working but it involves converting the circle to an equation of the form (x - cX)^2 + (y - cY)^2 = r^2 (where r is radius) and using the equation of the line from point (pX, pY) to (cX, cY) to create a quadratic equation to be solved.

Once I iron out the bugs it'll do, but it seems such an inelegant solution.


Solution

  • where P is the point, C is the center, and R is the radius, in a suitable "mathy" language:

    V = (P - C); Answer = C + V / |V| * R;
    

    where |V| is length of V.

    OK, OK

    double vX = pX - cX;
    double vY = pY - cY;
    double magV = sqrt(vX*vX + vY*vY);
    double aX = cX + vX / magV * R;
    double aY = cY + vY / magV * R;
    

    easy to extend to >2 dimensions.