mathbeziercubic-bezier

Given a cubic Bezier curve with fixed endpoints, how can I find the x position of a point along it when given a y position to check?


Let's say I have a Bezier curve with two fixed endpoints, one at x(0), y(1) and one at x(1), y(0) (bottom left corner and upper right corner) Now let's say I have two control points, which can be at any locations between x(0), x(1), y(0), and y(1). For this question, I'll just say that control point #1 is at x(0.1) y(0.6) and control point #2 is at x(0.9) and at y(0.4). (This assumes a "from upper left" coordinate system)

Here's a small illustration of our curve:

our bezier curve

Now let's say I'm given a y position of 0.7. What would the math look like to figure out what the corresponding x position is to the point at y(0.7)? How would I do this?


Sorry if this question doesn't belong here, but I figured this is a common problem faced in coding and that it's likely that many of you have the answer I'm looking for.


Solution

  • You have cubic equation for functions X(t) and Y(t) where t is curve parameter (range 0..1 for points on curve). In Bernstein polynomial basis (usual form for curve definition):

    X(t) = P0.X*(1-t)^3+3*P1.X*(1-t)^2*t+3*P2.X*(1-t)*t^2+P3.X*t^3
    Y(t) = P0.Y*(1-t)^3+3*P1.Y*(1-t)^2*t+3*P2.Y*(1-t)*t^2+P3.Y*t^3
    

    Having Y value, we can find corresponding t parameters - note there might be from 0 to 3 possible roots in range 0..1. Representation of Y-component in power basis:

    Y(t) = P0.Y*(1-t)^3+3*P1.Y*(1-t)^2*t+3*P2.Y*(1-t)*t^2+P3.Y*t^3 = 
           t^3*(P3Y-3P2Y+3P1Y-P0Y) + t^2*(3P2Y-6P1Y+3P0Y) + t^2*(3P1Y-3P0Y) + (P0Y) = 
           t^3*a + t^2*b + t^2*c + d' = y_position 
    

    and finally cubic equation is:

    t^3*a + t^2*b + t^2*c + d = 0
       where
    a = P3.Y-3*P2.Y+3*P1.Y-P0.Y
    b = 3*P2.Y-6*P1.Y+3*P0.Y
    c = 3*P1.Y-3*P0.Y
    d = P0.Y - y_position
    
     
    

    Solve cubic equation to calculate t (perhaps some values for wavy curves)

    Then for given t calculate corresponding X value:

    X(t) = P0.X*(1-t)^3+3*P1.X*(1-t)^2*t+3*P2.X*(1-t)*t^2+P3.X*t^3