Catmull Rom Spline implementation (LibGDX)

1.7k views Asked by At

I want to generate a random spline across my screen. Here is what I have so far:

public class CurvedPath {

Random rn;
CatmullRomSpline<Vector2> curve;

float[] xPts;
float[] yPts;
Vector2[] points;

public CurvedPath(){
    points = new Vector2[10];
    rn = new Random();
    curve = new CatmullRomSpline<Vector2>(points,false);

    for(int i = 0 ; i < 10; i++){
        xPts[i] = rn.nextFloat()*SampleGame.WIDTH;
        yPts[i] = SampleGame.HEIGHT*i/10;
    }


}

}

I'm pretty confused on the documentation that has been provided on how to use the CatmullRomSpline object ( https://github.com/libgdx/libgdx/wiki/Path-interface-&-Splines )

Basically what I am trying to do here is generate 10 random points equally distributed across the height of my screen, and randomly placed along the width of the screen to create a randomized curved path.

So within the constructor's for loop you can see that I generate the x and y values of each control point for the spline.

How can I give input these points into the spline object and render it on the screen?

-thanks

update Let me reword my question to be a little more specific..

I have my control points represented by xPts and yPts. Now I want to get the points that fall along the spline, how do I do this using these two vectors? The constructor for a CatmullRomSpline takes a Vector2, not two float[] 's

2

There are 2 answers

0
TomGrill Games On BEST ANSWER

what you did. Fill with points:

curve = new CatmullRomSpline<Vector2>(points,false);

To get a point on the curve:

Vector2 point = new Vector2();
curve.valueAt(point, 0.5f);

valueAt() Parameter explanation:

1 (point) the point you are looking for is stored in the Vector2 object.

  1. float between 0 and 1, 0 is the first point, 1 the last one. 0.5f is middle. This float represents the hole distance from first to last point.

Getting and render 100 points can look like this:

Vector2 point = new Vector2();
for (int i = 0; i <= 100; i++) {

    curve.valueAt(point, i * 0.01f);

    // draw using point.x and point.y
}

answer to you edited question:

for(int i = 0 ; i < 10; i++){
        points[i].x = rn.nextFloat()*SampleGame.WIDTH;
        points[i].y = SampleGame.HEIGHT*i/10;
}
curve = new CatmullRomSpline<Vector2>(points,false);
0
adeler On

The process is also detailed here: https://github.com/libgdx/libgdx/wiki/Path-interface-&-Splines

    /*members*/
    int k = 100; //increase k for more fidelity to the spline
    Vector2[] points = new Vector2[k];

    /*init()*/
    CatmullRomSpline<Vector2> myCatmull = new CatmullRomSpline<Vector2>(dataSet, true);
    for(int i = 0; i < k; ++i)
    {
        points[i] = new Vector2();
        myCatmull.valueAt(points[i], ((float)i)/((float)k-1));
    }