Note that for a cubic Bezier curve, there is no "one t
value for each coordinate". Cubic Bezier can self-intersect, so you can find multiple t
values for a single coordinate. There's two ways to do this: approximately or symbolically.
If you want an approximate answer (like what you're already doing for the length computation), simply construct a lookup table of coordinates-for-t:
buildLUT(a,b,c,d) {
for(t=0; t<=1; t+=0.01) {
LUTx[t*100] = getCoordinate(t, a.x,b.x,c.x,d.x);
LUTy[t*100] = getCoordinate(t, a.y,b.y,c.y,d.y);
}
}
And write an extra function for reverse lookups, or to build the reverse LUTs:
findTforCoordinate(x, y) {
found = []
for(i=0, len=LUTx.length; i<len; i++) {
_x = LUTx[i], _y = LUTy[i]
if(x==_x && y==_y) { found.push(i/len); }
}
return found
}
where a
,b
,c
,d
are your curve's control points. Since this is approximate, you're not looking for "t value for coordinate" but "closest t value to coordinate". It won't be perfect.
What WILL be perfect is finding all possible t
values for the x and y coordinate components, then finding the one or two t
values out of the set of possible six that approach generates that are the same between the x and y solutions. You can do this by using Cardano's approach, which is explain in another stackoverflow question here: Cubic Bezier reverse GetPoint equation: float for Vector <=> Vector for float