Code / Development / My Own Stuff / Unity September 25, 2013 @ 12:01

Clamped Bezier Spline for Unity

There are probably a many more of these BSpline implementstions to be found on the interwebs, so here’s another one:

using UnityEngine;

public class BSpline {
   
    private BSpline() { }
   
    public static Vector3 GetPoint(Vector3[] cvs, float t) {
        int segCount = cvs.Length - 1;
       
        float u = t * segCount;
        float v = u % 1;
        int seg = Mathf.FloorToInt(u);
       
        if (seg >= segCount) {
            v = 1;
            seg = segCount - 1;
        } else if (seg < 0) {
            v = 0;
            seg = 0;
        }
       
        Vector3 a, b, c ,d;
       
        if (seg == 0) {
            a = cvs[seg];
            b = cvs[seg];
            c = cvs[seg+1];
            d = cvs[seg+2];
        } else if (seg == segCount - 1) {
            a = cvs[seg-1];
            b = cvs[seg];
            c = cvs[seg+1];
            d = cvs[seg+1];
        } else {
            a = cvs[seg-1];
            b = cvs[seg];
            c = cvs[seg+1];
            d = cvs[seg+2];
        }
       
        return curveFunction(a, b, c, d, v);
    }
   
    private static Vector3 curveFunction(Vector3 a, Vector3 b,
            Vector3 c, Vector3 d, float t) {
        float it = 1 - t;
        float t2 = t * t;
        float t3 = t2 * t;
        float b0 = it * it * it / 6;
        float b1 = (3 * t3 - 6 * t2 + 4) / 6;
        float b2 = (-3 * t3 + 3 * t2 + 3 * t + 1) / 6;
        float b3 = t3 / 6;
        return b0 * a + b1 * b + b2 * c + b3 * d;
    }
}
No Comments to Clamped Bezier Spline for Unity

Add comment:


You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

By submitting a comment here you grant baseone:online a perpetual license to reproduce your words and name/web site in attribution. Inappropriate or irrelevant comments will be removed at an admin's discretion.