# Closest point on circle edge from point outside/inside the circle

Alright, I am programming a plugin for a game that requires me to get the closest point on a circle when all you have is a point B, which is outside of the circle, the radius of the circle, and the location of the center of the circle.

Say I have this situation:

So, how would I be able to get the coordinates of point C? I need a formula that allows me to calculate those coordinates when I only know the radius of the circle and the coordinates of B. I sketched the line for ease of understanding, but all I start with is just the circle and point B. OH, one other thing, B isn't a static point, each time this calculation will be executed B will be at another position.

And, as a bonus (not really needed) would you care to show an example on how to do the same thing, but then when point B is inside the circle.

-
That is useful to me too. But what if instead of a circle, it is an ellipse? – user31689 May 18 '12 at 16:55
You should post this as a separate question, so that people can post answers to it using the answer box. I think you are going to have to solve a system of 2 quadratic equations: one is your equation of the ellipse $ax^2+by^2=1$, the other is $by(x-p)-ax(y-q)=0$ where $(p,q)$ is the point outside of ellipse. The second equation expresses the orthogonality of the vector $\langle x-p,y-q \rangle$ to the ellipse. The case of the circle is much easier because when $a=b$, the second equation is linear. – user31373 May 18 '12 at 17:09
This can be "reduced" to solving a quartic equation. Note that there can be two local minima and two local maxima. – Robert Israel May 18 '12 at 17:16
Note The two prior comments (of LK and RI) apply to Brad's comment (which was migrated from an answer). – Bill Dubuque May 18 '12 at 17:30

$$\vec C = \vec A + r\frac{(\vec B - \vec A)}{||\vec B - \vec A||}$$ Where $r$ is the radius of the circle. Works for points both inside and outside the circle. Imagine $(\vec B - \vec A)$ to be a vector in the direction of $\vec B$ and $\frac{(\vec B - \vec A)}{||\vec B - \vec A||}$ thus is the same vector but with a length of $1$. By multiplying it with $r$, you "walk in that direction" a total distance of $r$, thus reaching the circle.
With coordinats $\vec A = (A_x, A_y)$ etc. this reads $$C_x = A_x + r\frac{B_x-A_x}{\sqrt{(B_x-A_x)^2+(B_y-A_y)^2}}$$ $$C_y = A_y + r\frac{B_y-A_y}{\sqrt{(B_x-A_x)^2+(B_y-A_y)^2}}$$
@Quincy: This will get you the point on the circle. I assumed that is what you wanted? (using the letters $A$, $B$ and $C$ as they appear in your plot) – example Apr 3 '12 at 14:03
@Quincy: Don't worry, no question is every stupid ;) The fault is on my part. The formula is correct, but I used $\vec A$ as the center of the circle, $\vec C$ as the point outside and $\vec B$ as the point on the circle. Will change it to use your names for the points. – example Apr 3 '12 at 14:12