Calculating the reflection of a point over a line

Given a point \(P\), it is quite easy to calculate its reflection (a point \(R\)) over a line of symmetry. This post relies upon the basics of vectors that have been defined previously.

Perhaps the most common scenario for mirroring is in computer graphics. Pixel shaders use this principle to compute how the rays of light bounce off surfaces.

In video games, it can also be used to predict the trajectory of an object when trying to simulate its physics. Likewise, it could also be used to synchronise the position of two elements on screen.

How to calculate \(R\)?

First, let's consider the line1 2 \(\overline{AB}\) and any two points on it, \(A\) and \(B\). They are interchangeable but, for the purposes of this post, we'll be using \(A\).

We must now obtain a unit vector \(\vec{N}\) out of \(\overline{AB}\). This vector will be parallel to the line.

\[ \vec{N} = \frac{B-A}{\|B-A\|} \]

Any two points on the line will suffice, no matter the distance separating them.

Next, we'll need to calculate \(Q\), the midpoint between \(P\) and our future \(R\). This point also has a nice property: it is the result of the projection of \(P\) on the line.

In order for the math to make sense, we'll need to find a vector that represents the position of \(P\) relative to the line. This vector is \(P-A\). With it, we then calculate its shadow3 over \(\vec{N}\).

We can then trivially find our point by offsetting the start of the line, \(A\), by that amount.

\[ Q = A + ((P-A) \cdot \vec{N})\vec{N} \]

Q lies at the end of the projection of P on the line

The following step requires us to find the offset between \(P\) and \(Q\). Since the reflection is symmetrical, that offset will be the same on both sides – it can be applied twice4 to \(P\).

\[ \begin{aligned}R &= P + 2(Q - P) \\ R &= 2Q - P \end{aligned} \]

Notice that the line that passes through P and Q is perpendicular to our symmetry line

Finally, everything can be bundled into a single equation by substituting \( Q \):

\[ R= 2(A + ((P-A) \cdot \vec{N})\vec{N}) - P \]

Often the rain in life shows us the best reflection of who we truly are.
Photo by Todd Trapani / Unsplash

1 In reality, we only need a starting point \(A\) and a vector \(\vec{N}\) representing the slope of the line. By starting out with that information, we can just skip this step.

2 When modelling the light or an object bouncing off a surface, \(A\) is the point of impact and \(N\) is the normal of such surface.

3 We are projecting unto a unit vector, thus the original projection equation \( \frac{(P-A) \cdot \vec{N}}{\|\vec{N}\|} \) is simplified to just \((P-A) \cdot \vec{N}\). Unit vectors have, by definition, a magnitude of \(1\).

4 Since \(Q\) is the midpoint between \(P\) and \(R\), this can also be imaged as offsetting \(Q\) by \( \overrightarrow{PQ} \) once.