Libgdx 之贝塞尔曲线

来源:互联网 发布:sql group by 多列 编辑:程序博客网 时间:2024/05/22 11:55

Libgdx 之贝塞尔曲线

贝塞尔曲线,游戏开发中,常用于物体的运动轨迹、路径、以及一些特效的实现

注:公式来源网络

线性:

二次:


三次:



在Libgdx中,就自带关于Bezier的实现,以下是本人对公式的实现

P以Verctor2表示,为点坐标

/**  * 构建贝塞尔曲线类  * @author whs  *  */public abstract class Bezier {protected Vector2 tmpVec;public abstract Vector2 apply(float f);public Bezier() {tmpVec = new Vector2();}public static Bezier cubic(float x1, float y1, float x2, float y2, float x3,float y3, float x4, float y4) {return cubic(new Vector2(x1, y1), new Vector2(x2, y2), new Vector2(x3,y3), new Vector2(x4, y4));}public static Bezier cubic(Vector2 p0, Vector2 p1,Vector2 p2, Vector2 p3) {return new CubicBezier(p0, p1, p2, p3);}public static Bezier linear(float x1, float y1, float x2, float y2) {return linear(new Vector2(x2, y1), new Vector2(x2, y2));}public static Bezier linear(Vector2 p0, Vector2 p1) {return new LinearBezier(p0, p1);}public static Bezier quadratic(float x1, float y1, float x2, float y2, float x3,float y3) {return quadratic(new Vector2(x1, y1), new Vector2(x2, y2), new Vector2(x3,y3));}public static Bezier quadratic(Vector2 p0, Vector2 p1,Vector2 p2) {return new QuadraticBezier(p0, p1, p2);}/** * 三次方贝塞尔曲线 * @author whs * */public static class CubicBezier extends Bezier {public Vector2 p0;public Vector2 p1;public Vector2 p2;public Vector2 p3;public CubicBezier(Vector2 p0, Vector2 p1,Vector2 p2, Vector2 p3) {this.p0 = p0;this.p1 = p1;this.p2 = p2;this.p3 = p3;}public Vector2 apply(float f) {float f1 = 1.0F - f;float f2 = f * f;float f3 = f1 * f1;float f4 = f3 * f1;float f5 = f * (3F * f3);float f6 = f2 * (3F * f1);float f7 = f2 * f;tmpVec.x = f4 * p0.x + f5 * p1.x + f6 * p2.x + f7 * p3.x;tmpVec.y = f4 * p0.y + f5 * p1.y + f6 * p2.y + f7 * p3.y;return tmpVec;}}/** * 线性贝塞尔曲线 * @author whs * */public static class LinearBezier extends Bezier {public Vector2 p0;public Vector2 p1;public LinearBezier(Vector2 p0, Vector2 p1) {    this.p0 = p0;    this.p1 = p1;}public Vector2 apply(float f) {float f1 = 1.0F - f;tmpVec.x = f1 * p0.x + f * p1.x;tmpVec.y = f1 * p0.y + f * p1.y;return tmpVec;}}/** * 二次贝塞尔去选 * @author whs * */public static class QuadraticBezier extends Bezier {public Vector2 p0;public Vector2 p1;public Vector2 p2;public QuadraticBezier(Vector2 p0, Vector2 p1,Vector2 p2) {this.p0 = p0;this.p1 = p1;this.p2 = p2;}public Vector2 apply(float f) {float f1 = 1.0F - f;float f2 = f1 * f1;float f3 = f * (2.0F * f1);float f4 = f * f;tmpVec.x = f2 * p0.x + f3 * p1.x + f4 * p2.x;tmpVec.y = f2 * p0.y + f3 * p1.y + f4 * p2.y;return tmpVec;}}}


Bezier曲线的应用:

Bezier myBezier = Bezier .cubic(point_start,point_control_1 ,point_control_2,point_end);

根据时间的变化,得到曲线上的点的位置,time的取值为0 <= time && time < =1

vector2 = myBezier.apply(time);

当然,传入的参数不一定是时间,例如控制时间为10s,那么便是time / 10,当然,如果需要实现轨迹的路线,可直接给time初始化为常量

贝塞尔曲线实现较简单,使用的效果当然由使用者掌控



0 0
原创粉丝点击