I have a Bezier curve: (0,0)
, (.25,.1)
, (.25,1)
, and (1,1)
.
This is graphically seen here: http://cubic-bezier.com/#.25,.1,.25,1
We see on the x axis is time.
This is my unknown. This is a unit cell. So I was wondering how can I get x when y is 0.5?
Thanks
I saw this topic: y coordinate for a given x cubic bezier
But it loops, I need to avoid something loops So I found this topic: Cubic bezier curves - get Y for given X
But I can't figure out how to solve a cubic polynomial in js :(
All the solutions that use a look up table can only give you an approximate result. If that is good enough for you, you are set. If you want a more accurate result, then you need to use some sort of numeric method.
For a general Bezier curve of degree N, you do need to loop. Meaning, you need to use bi-section method or Newton Raphson method or something similar to find the x value corresponding to a given y value and such methods (almost) always involve iterations starting with an initial guess. If there are mutiple solutions, then what x value you get will depend on your initial guess.
However, if you only care about cubic Bezier curves, then analytic solution is possible as roots of cubic polynomials can be found using the Cardano formula. In this link (y coordinate for a given x cubic bezier), which was referenced in the OP, there is an answer by Dave Bakker that shows how to solve cubic polynomial using Cardano formula. Source codes in Javascript is provided. I think this will be your good source to start your investigation on.
This is mathematically impossible unless you can guarantee that there will only be one
y
value perx
value, which even on a unit rectangle you can't (for instance, {0,0},{1,0.6},{0,0.4},{1,1} will be rather interesting at the mid point!). The fastest is to simply build a LUT, like for instance:Done, now if you want to look up an
x
value for somey
value, just run throughLUT_y
until you find youry
value, or more realistically until you find two values at indexi
andi+1
such that youry
value lies somewhere in between them, and you will immediately know the correspondingx
value because it'll be at the same index inLUT_x
.For nonexact matches with 2 indices
i
andi+1
you simply do a linear interpolation (i.e.y
is at distance ... betweeni
andi+1
, and this at the same distance betweeni
andi+1
for thex
coordinates)Thanks again to Mike's help we found the fastest way to do this. I put this function togather, takes 0.28msg on average: