CatmullRomSplines and other smooth paths

4.4k views Asked by At

I've been looking into getting an object on a two dimensional plane to follow a smooth curve defined by several control points.From what I've found, I'm looking for a Catmull-Rom-Spline.

I've been using LibGDX for my project, and it has its own Catmull-Rom-Spline implementation but I'm having trouble wrapping my head around how it works, as I've had trouble finding documentation or other source code implementing Catmull-Rom-Splines using LibGDX.

I'm looking for either an explanation of the LibGDX Catmull-Rom-Spline implementation or another way to implement a smooth path that implements control points using Catmull-Rom-Splines or another method. All I'm looking for is the ability to generate a path and pass back the x and y coordinates of a point on that path. If anyone has any suggestions or pointers, it would be appreciated. Thanks.

1

There are 1 answers

3
Xoppa On BEST ANSWER

The libgdx Path classes (including CatmullRomSpline) are suitable for both 2D and 3D. So when creating a CatmullRomSpline, you must specify which Vector (Vector2 or Vector3) to use:

CatmullRomSpline<Vector2> path = new CatmulRomSpline<Vector2> ( controlpoints, continuous );

For example:

float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
Vector2 cp[] = new Vector2[]{
    new Vector2(0, 0), new Vector2(w * 0.25f, h * 0.5f), new Vector2(0, h), new Vector2(w*0.5f, h*0.75f),
    new Vector2(w, h), new Vector2(w * 0.75f, h * 0.5f), new Vector2(w, 0), new Vector2(w*0.5f, h*0.25f)
};
CatmullRomSpline<Vector2> path = new CatmullRomSpline<Vector2>(cp, true);

Now you can get the location on the path (ranging from 0 to 1) using the valueAt method:

Vector2 position = new Vector2();
float t = a_vulue_between_0_and_1;
path.valueAt(position, t);

For example:

Vector2 position = new Vector2();
float t = 0;
public void render() {
    t = (t + Gdx.graphics.getDeltaTime()) % 1f;
    path.valueAt(position, t);
    // Now you can use the position vector
}

Here's an example: https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/PathTest.java