Search code examples
javalibgdx

Drawing curves using libgdx


I'm using libgdx trying to draw some curves using this doc.

But when I render, its just a straight line, any ideas why it doesn't curve?

I'm assuming myCatmull.valueAt should populate correct points on curve.

public class IABezier {

    Vector2[] points = new Vector2[100];

    public IABezier() {

        Vector2[] dataSet = new Vector2[2];
        dataSet[0] = new Vector2(10.0f, 10.0f);
        dataSet[1] = new Vector2(20.0f, 20.0f);

        CatmullRomSpline < Vector2 > myCatmull = new CatmullRomSpline < Vector2 > (dataSet, true);
        for (int i = 0; i < 100; ++i) {

            points[i] = new Vector2();
            myCatmull.valueAt(points[i], ((float) i) / ((float) 100 - 1));
        }
    }

    public void draw(ShapeRenderer sRenderer) {

        sRenderer.begin(ShapeType.Line);
        sRenderer.identity();
        for (int i = 0; i < 100 - 1; ++i) {

            sRenderer.line(points[i], points[i + 1]);
        }
        sRenderer.end();
    }
}

Rendered ..

screenshot


Solution

  • A catmullrom spline requires at least four samples. So you'll have to add a few more samples to see the actual curve.

        Vector2[] dataSet = new Vector2[6];
        dataSet[0] = new Vector2(10.0f, 10.0f);
        dataSet[1] = new Vector2(20.0f, 20.0f);
        dataSet[2] = new Vector2(20.0f, 10.0f);
        dataSet[3] = new Vector2(10.0f, 20.0f);
        dataSet[4] = new Vector2(15.0f, 15.0f);
        dataSet[5] = new Vector2(25.0f, 25.0f);
    

    Here's an example which you can copy, paste and run.