How to get the slope of a tangent to a circle from a point always oriented in the same way

analytic geometrycalculus

Given a circle (defined through its center $(x_c,y_c)$ and radius $r$) and an external point $(x_0, y_0)$ , I am looking for the heading of one of the two tangents (I know how to select the one I need case-by-case) such that if I write the tangent line in the parametric form

$$ x(t) = x_0 + t \cdot \sin(heading) $$
$$ y(t) = y_0 +t \cdot \cos(heading) \, , $$
I want the tangent point to be in the range $t<0$.

NOTE: the parametric equation is given to explain the desired orientation of the heading. I need the heading defined in that way.

I have read this answer and it mostly works fine, but there are some cases in my application where the function given provides $heading +\pi$:

$$vec = [r:\mp\sqrt{(y_0 – y_c)^2+(x_0 – x_c)^2-r^2}:-\sqrt{(y_0 – y_c)^2+(x_0 – x_c)^2}] \begin{bmatrix}(y_0 – y_c)&(x_0 – x_c)&-x_c(y_0 – y_c)-y_c(x_0 – x_c)\\ -(x_0 – x_c)&(y_0 – y_c)&x_c(x_0 – x_c)-y_c(y_0 – y_c) \\ 0&0&r\sqrt{(y_0 – y_c)^2+(x_0 – x_c)^2}\end{bmatrix}$$

$$heading = \arctan_2(vec(1),vec(2))$$

Question: how can I fix this function so that I always obtain the desired value for the heading?

Best Answer

Expanding on my comment, there is a circle with centre $C$ and radius $r$, an external point $P$, and two tangent points $T_+$ (to the right from $P$, anti-clockwise around $C$) and $T_-$ (to the left from $P$, clockwise around $C$). (Note: we are using the standard coordinate system with $\theta = 0$ starting at the $x$-axis and increasing anti-clockwise.) You want to quantify the direction of travel $\alpha_\pm$ heading away from $T_\pm$.

First we find the tangent points $$ T_\pm = C + \underbrace{\frac{r}{\Vert P - C \Vert}}_{\text{scale}} \cdot \underbrace{R(\pm\theta)}_{\text{rotate}} \cdot (P - C), $$ where $$ R(\pm\theta) = \begin{bmatrix} \cos\theta & \mp\sin\theta \\ \pm\sin\theta & \cos\theta \end{bmatrix} $$ is the general rotation matrix and $$ \cos\theta = \frac{r}{\Vert P - C \Vert}, \quad \sin\theta = \sqrt{1 - \cos^2 \theta}, \quad \left(0 \le \theta \le \frac{\pi}{2}\right) $$ by observing the right triangle $C T_+ P$. Then the required heading is $$ \alpha_\pm = \text{atan2}(P - T_{\pm}). $$


We can also make the formula more compact. Let $$ \lambda = \tan\theta = \frac{\sin\theta}{\cos\theta} = \sqrt{\frac{\Vert P - C \Vert^2}{r^2} - 1}, $$ then some algebraic manipulation gives $$ \alpha_\pm = \text{atan2}\left( \begin{bmatrix} \lambda & \mp 1 \\ \pm 1 & \lambda \end{bmatrix} (P - C) \right). $$