Find value of '$t$' at a point on a cubic Bezier curve

Solution 1:

Suppose we let $\mathbf{P}(t)$ be the Bezier curve, and let the given point be $\mathbf{B}$.

In theory, we want to find a value of $t$ such that $\mathbf{P}(t) = \mathbf{B}$. If you write out the $x$ and $y$ components separately, this will give you two cubic equations, which should have a common root, $t$.

But, in floating point arithmetic, $\mathbf{B}$ will be some small distance away from the curve, and we need to accomodate this. So, a better approach is to find the point on the curve that is closest to $\mathbf{B}$. In other words, find the value of $t$ that minimises the distance from $\mathbf{B}$ to $\mathbf{P}(t)$. At the point where this happens, the vector $\mathbf{P}(t) - \mathbf{B}$ will be perpendicular to the curve tangent, so $$ (\mathbf{P}(t) - \mathbf{B}) \cdot \mathbf{P}'(t) = 0 $$ Since $\mathbf{P}(t)$ is cubic and $\mathbf{P}'(t)$ is quadratic, this is an equation of degree 5 in $t$, which you can solve using your favorite numerical root-finder. This is the brain-dead brute force approach.

Now a smarter way ...

If you look in these notes by Tom Sederberg, you will find some techniques for "inversion" of polynomial and rational curves, based on the use of resultants. Specifically, on page 200, you will find a formula for doing "inversion" of a cubic curve written in Bezier form, and there's a nice worked example on page 201. This is exactly what you need.

As I mentioned above, you will often meet cases where the given point $\mathbf{B}$ is not exactly on the curve. You can apply the inversion formula, anyway, and it will give you some value of $t$. I'm not 100% sure what point this value of $t$ represents. I don't think it's the point on the curve that's closest to $\mathbf{B}$, but it should be good enough if $\mathbf{B}$ is already very close to the curve.

Solution 2:

This is function for cubic bezier

$p = p_0(1 - t)^3 + 3p_1t(1 - t)^2 + 3p_2t^2(1 - t) + p_3t^3$

It can be reaarange into

$ p = p_0(1 - 3t + 3t^2 - t^3) + 3p_1(t - 2t^2 + t^3) + 3p_2(t^2 - t^3) + p_3t^3 \\ t^3(p_3 - 3p_2 + 3p_1 - p_0) + t^23(p_2 - 2p_1 + p_0) + t3(p_1 - p_0) + p_0 - p = 0 $

From this point it's a cubic equation for $x$ and $y$

You can find $t$ from $x$ and cubic equation will result in 3 possible values. Then you put $t$ back into function to get 3 $y$ and select a value close to the $y$ you put in