Cubic bezier curves - get Y for given X

Peter W. picture Peter W. · Nov 21, 2011 · Viewed 8.1k times · Source

I have a cubic bezier curve where the first and last points are given (namely P0(0,0) and P3(1,1)). The other two points are defined like this: cubic-bezier(0.25, 0.1, 0.25, 1.0) (X1, Y1, X2, Y2, also those values must not be smaller or larger than 0 or 1, respectively)
Now what would I have to do to get the Y coordinate for a given X, assuming there's only one? (I know that under certain circumstances there can be multiple values, but let's just put them aside. I'm not doing rocket science over here, I just want to be able to get Y multiple times per second to do transitions)

I managed to dig up this: y coordinate for a given x cubic bezier, but I don't understand what xTarget stands for.
Oh, also this is no homework whatsoever, I'm just a bit annoyed at the fact that there's no comprehensible stuff about cubic bezier curves on the internet.

Answer

JohnPS picture JohnPS · Nov 21, 2011

If you have

P0 = (X0,Y0)
P1 = (X1,Y1)
P2 = (X2,Y2)
P3 = (X3,Y3)

Then for any t in [0,1] you get a point on the curve given by the coordinates

X(t) = (1-t)^3 * X0 + 3*(1-t)^2 * t * X1 + 3*(1-t) * t^2 * X2 + t^3 * X3
Y(t) = (1-t)^3 * Y0 + 3*(1-t)^2 * t * Y1 + 3*(1-t) * t^2 * Y2 + t^3 * Y3

If you are given an x value, then you need to find which t values in [0,1] correspond to that point on the curve, then use those t values to find the y coordinate.

In the X(t) equation above, set the left side to your x value and plug in X0, X1, X2, X3. This leaves you with a cubic polynomial with variable t. You solve this for t, then plug that t value into the Y(t) equation to get the y coordinate.

Solving the cubic polynomial is tricky but can be done by carefully using one of the methods to solve a cubic polynomial.