贝塞尔曲线

来源:互联网 发布:怪物猎人p3数据 编辑:程序博客网 时间:2024/05/20 06:23


贝塞尔曲线(Bézier curve)于1962,由法国工程师皮埃尔·贝塞尔(Pierre Bézier)所广泛发表,他运用贝塞尔曲线来为汽车的主体进行设计。贝塞尔曲线最初由Paul de Casteljau于1959年运用de Casteljau演算法开发,以稳定数值的方法求出贝兹曲线。
它是依据四个位置任意的点坐标绘制出的一条光滑曲线。曲线必定通过首尾两个点,称为端点;中间两个点虽然未必要通过,但却起到牵制曲线形状路径的作用,称作控制点。








之前在网上看到一段代码,出处忘记了,但是很好用,代码如下:


//绘制路径public void DrawPathHelper(Vector3[] path, Color color){SmoothSens = 50;  //曲线平滑度lineRenderer = GetComponent<LineRenderer>();lineRenderer.SetVertexCount(SmoothSens*vvvv.Count+1);//设置线段数lineRenderer.SetWidth(0.1f, 0.1f);//设置曲线宽度Vector3[] vector3s = PathControlPointGenerator(path);//路径控制点生成Vector3 prevPt = Interp(vector3s,0);Gizmos.color=color;int SmoothAmount = path.Length*SmoothSens;for (int i = 1; i <= SmoothAmount; i++) {float pm = (float) i / SmoothAmount;Vector3 currPt = Interp(vector3s,pm);lineRenderer.SetPosition(i-1, currPt);lineRenderer.SetPosition(i, prevPt);prevPt = currPt;}}public Vector3[] PathControlPointGenerator(Vector3[] path){Vector3[] suppliedPath;//提供的路径Vector3[] vector3s;//create and store path points:创建储备路径点suppliedPath = path;//populate calculate path;计算构成路径int offset = 2;vector3s = new Vector3[suppliedPath.Length+offset];Array.Copy(suppliedPath,0,vector3s,1,suppliedPath.Length);//将suppliedPath的0部分元素复制到vector3s中1部分,复制length长度//populate start and end control points:vector3s[0] = vector3s[1] + (vector3s[1] - vector3s[2]);vector3s[vector3s.Length-1] = vector3s[vector3s.Length-2] + (vector3s[vector3s.Length-2] - vector3s[vector3s.Length-3]);//is this a closed, continuous loop? yes? well then so let's make a continuous Catmull-Rom spline!if(vector3s[1] == vector3s[vector3s.Length-2]){Vector3[] tmpLoopSpline = new Vector3[vector3s.Length];Array.Copy(vector3s,tmpLoopSpline,vector3s.Length);tmpLoopSpline[0]=tmpLoopSpline[tmpLoopSpline.Length-3];tmpLoopSpline[tmpLoopSpline.Length-1]=tmpLoopSpline[2];vector3s=new Vector3[tmpLoopSpline.Length];Array.Copy(tmpLoopSpline,vector3s,tmpLoopSpline.Length);}return(vector3s);}public Vector3 Interp(Vector3[] pts, float t){int numSections = pts.Length - 3;int currPt = Mathf.Min(Mathf.FloorToInt(t * (float) numSections), numSections - 1);float u = t * (float) numSections - (float) currPt;Vector3 a = pts[currPt];Vector3 b = pts[currPt + 1];Vector3 c = pts[currPt + 2];Vector3 d = pts[currPt + 3];return .5f * ((-a + 3f * b - 3f * c + d) * (u * u * u)+ (2f * a - 5f * b + 4f * c - d) * (u * u)+ (-a + c) * u+ 2f * b);}


0 0