Skip to content

Instantly share code, notes, and snippets.

@Madsy
Last active October 27, 2016 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Madsy/8f117a36bca0a2fbc3e33254dceaa12a to your computer and use it in GitHub Desktop.
Save Madsy/8f117a36bca0a2fbc3e33254dceaa12a to your computer and use it in GitHub Desktop.
c*x^2-2*b*x^2+a*x^2+2*b*x-2*a*x+a
Derive formula for quadratic bezier curve:
Interpolate from start point towards control point:
v1 = a + (b-a)*t
Interpolate from control point towards end point:
v2 = b + (c-b)*t
Interpolate between the two points computed from v1 and v2 (v is our point on the curve for any t in [0, 1]):
v = v1 + (v2 - v1)*t
Expand and then simplify and rearrange the formula:
v = a + (b-a)*t + ((b + (c-b)*t) - (a + (b-a)*t))*t
v = a + b*t - a*t + ((b + c*t - b*t) - (a + b*t - a*t))*t
v = a + b*t - a*t + b*t - a*t + a*t*t + c*t*t - 2*b*t*t
v = a*t*t - 2*b*t*t + c*t*t -2*a*t + 2*b*t + a
v = at^2 - 2bt^2 + ct^2 - 2at + 2bt + a
For a point on a 2D curve we get a parametric function:
x = f1(t) := at^2 - 2bt^2 + ct^2 - 2at + 2bt + a
y = f2(t) := dt^2 - 2et^2 + ft^2 - 2dt + 2et + d
Tangents for the curve are the derivatives of the functions:
f1'(t) = 2at - 4bt + 2ct - 2a + 2b
f2'(t) = 2dt - 4et + 2ft - 2d + 2e
PROBLEM: To find the point [x,y] on a quadratic curve closest to a point [px,py] (which is not on the curve)
The normal of the point [x,y] is peripendecular to the tangent of the curve. So we can take the dot product:
(f1(t) - px)*f1'(t) + (f2(t) - py)*f2'(t) = 0
..or in other words: dp = f(t) - p
Expand to cubic equation:
(at^2 - 2bt^2 + ct^2 - 2at + 2bt + a - px)*(2at - 4bt + 2ct - 2a + 2b) + (dt^2 - 2et^2 + ft^2 - 2dt + 2et + d - py)*(2dt - 4et + 2ft - 2d + 2e) = 0
(2*a^2-8*a*b+8*b^2+(4*a-8*b)*c+2*c^2+2*d^2-8*d*e+8*e^2+(4*d-8*e)*f+2*f^2)*t^3+
(-6*a^2+18*a*b-12*b^2+(6*b-6*a)*c-6*d^2+18*d*e-12*e^2+(6*e-6*d)*f)*t^2+
(6*a^2-12*a*b+4*b^2+2*a*c+6*d^2-12*d*e+4*e^2+2*d*f+(-2*c+4*b-2*a)*px+(-2*f+4*e-2*d)*py)*t
+(2*d-2*e)*py+(2*a-2*b)*px+2*d*e-2*d^2+2*a*b-2*a^2 = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment