Grav
Grav

Reputation: 491

What's wrong with my bezier curve?

I'm drawing a quadratic bezier curve, and I'm not sure why it's behaving the way that it is. It almost appears as if there's another control point influencing the curve, but there are only 3 control points, and the formula is only for quadratic curves.

Here are some images of what it's doing: https://i.sstatic.net/zphds.jpg

And code:

Point Bezier::evaluate(float t)
{
    //  [x,y]=(1–t)^2*2P0+2(1–t)t*P1+t^2*P2

    Point P;
    P.x = (1 - t)*(1 - t)*points[0].x +
          2*(1 - t)*(1 - t)*t*points[1].x +
          t*t*points[2].x;

    P.y = (1 - t)*(1 - t)*points[0].y +
          2*(1 - t)*(1 - t)*t*points[1].y +
          t*t*points[2].y;

    return P;
}

void Bezier::drawCurve()
{
    glColor3d(red, green, blue);
    Point lastPoint = points[0];

    for (float t = 0.0; t <= 1.0; t += 0.01)
    {
        Point currentPoint = evaluate(t);
        drawLine(lastPoint.x, lastPoint.y, currentPoint.x, currentPoint.y);
        lastPoint = currentPoint;
    }
}

void Bezier::drawHandles()
{
    glColor3d(red, green, blue);

    for (int i = 0; i < 3; i++)
    {
        drawCircle(points[i].x, points[i].y, points[i].radius);
    }
}

Header

class Point
{
    public:
        float x;
        float y;
        float radius = 5;
};

class Bezier
{
    public:
        Bezier(float startX, float startY, float endX, float endY, float red, float green, float blue);
        Point evaluate(float time);
        void drawCurve();
        void drawHandles();

        Point points[3];

        float red;
        float green;
        float blue;
};

Thanks in advance for any help!

Upvotes: 0

Views: 470

Answers (1)

hugos
hugos

Reputation: 1323

The formula you're using is wrong

P.x = (1 - t)*(1 - t)*points[0].x +
      2*(1 - t)*t*points[1].x +
      t*t*points[2].x;

P.y = (1 - t)*(1 - t)*points[0].y +
      2*(1 - t)*t*points[1].y +
      t*t*points[2].y;

You have an extra (1-t) in the second term.

Upvotes: 6

Related Questions