How to find $x$ by $y$ in bezier curve.

61 Views Asked by At

I draw the lines connecting the different nodes on the screen with the cubic bezier curve. These lines must be suitable for interaction. So I need to know how close the user is to the line based on the mouse's position.

cubic

First, let's name the elements in the image.

$\color{Blue}blue : P_{1}$
$\color{Orange}orange : P_{2}$
$\color{Pink}pink : P_{3}$
$\color{Green}green : P_{4}$

The small green dots are the $[x(t),y(t)]$ points for $ 0 \leqslant t \leqslant 1 $ calculated with the following functions (written with dart):

  double x(double t) {
    return (cu(1 - t) * x1) +
           (3 * t * sq(1 - t) * x2) +
           (3 * sq(t) * (1 - t) * x3) +
           (cu(t) * x4);
  }

  double y(double t) {
    return (cu(1 - t) * y1) +
           (3 * t * sq(1 - t) * y2) +
           (3 * sq(t) * (1 - t) * y3) +
           (cu(t) * y4);
  }

$\left [ y_{1} = y_{2} \right ] \land \left [ y_{3} = y_{4} \right ]$

So, There is only one $x$ : $\forall_{y} \in \left [ y_{1} \leqslant y \leqslant y_{4} \right]$.

Based on this proposition;

(mouse offset from top left: $m$, height: $h$)

$ h = |y_{1} - y_{4}|$

$ t = \dfrac{m_{y} - min(y_{1} , y_{4})}{h}$

$ x = cubic.x(t)$

$ y = cubic.y(t)$

If the mouse is closer to this $[x,y]$ point than $tolerance$ (The purple circle in the gif, $r = tolerance, o = [x,y]$), I understand it's on the line.

I expect that the $y$ have to equal $m_{y}$. But it is not.

But this point is wrong. Here is the result I got:

gif

What am I doing wrong?