To get an individual point (x, y)
along a cubic curve at a given percent of travel (t)
, with given control points (x1, y1)
, (x2, y2)
, (x3, y3)
, and (x4, y4)
I expanded De Casteljau’s algorithm and rearranged the equation to minimize exponents:
//Generalized code, not C++
variables passed to function: t, x1, y1, x2, y2, x3, y3, x4, y4
variables declared in function: t2, t3, x, y
t2 = t * t
t3 = t * t * t
x = t3*x4 + (3*t2 - 3*t3)*x3 + (3*t3 - 6*t2 + 3*t)*x2 + (3*t2 - t3 - 3*t + 1)*x1
y = t3*y4 + (3*t2 - 3*t3)*y3 + (3*t3 - 6*t2 + 3*t)*y2 + (3*t2 - t3 - 3*t + 1)*y1
(t)
is a decimal value between 0 and 1 (0 <= t <= 1)
that represents percent of travel along the curve.
The formula is the same for x and y, and you can write a function that takes a generic set of 4 control points or group the coefficients together:
t2 = t * t
t3 = t * t * t
A = (3*t2 - 3*t3)
B = (3*t3 - 6*t2 + 3*t)
C = (3*t2 - t3 - 3*t + 1)
x = t3*x4 + A*x3 + B*x2 + C*x1
y = t3*y4 + A*y3 + B*y2 + C*y1
For quadratic functions, a similar approach yields:
t2 = t * t
A = (2*t - 2*t2)
B = (t2 - 2*t + 1)
x = t2*x3 + A*x2 + B*x1
y = t2*y3 + A*y2 + B*y1