最近使用unity制作了绘图板的功能,不过线段绘制的时候一直不平滑,怎么使线段平滑呢?类似下图:
使用该代码即可返回平滑的点
//arrayToCurve is original Vector3 array, smoothness is the number of interpolations.
public static Vector3[] MakeSmoothCurve(Vector3[] arrayToCurve,float smoothness){
List<Vector3> points;
List<Vector3> curvedPoints;
int pointsLength = 0;
int curvedLength = 0;
if(smoothness < 1.0f) smoothness = 1.0f;
pointsLength = arrayToCurve.Length;
curvedLength = (pointsLength*Mathf.RoundToInt(smoothness))-1;
curvedPoints = new List<Vector3>(curvedLength);
float t = 0.0f;
for(int pointInTimeOnCurve = 0;pointInTimeOnCurve < curvedLength+1;pointInTimeOnCurve++){
t = Mathf.InverseLerp(0,curvedLength,pointInTimeOnCurve);
points = new List<Vector3>(arrayToCurve);
for(int j = pointsLength-1; j > 0; j--){
for (int i = 0; i < j; i++){
points[i] = (1-t)*points[i] + t*points[i+1];
}
}
curvedPoints.Add(points[0]);
}
return(curvedPoints.ToArray());
}
使用方法:
//javascript/unityscript example
#pragma strict
var points : Vector3[];
var lineRenderer : LineRenderer;
var c1 : Color = Color.yellow;
var c2 : Color = Color.red;
function Start () {
points = Curver.MakeSmoothCurve(points,3.0);
lineRenderer.SetColors(c1, c2);
lineRenderer.SetWidth(0.5,0.5);
lineRenderer.SetVertexCount(points.Length);
var counter : int = 0;
for(var i : Vector3 in points){
lineRenderer.SetPosition(counter, i);
++counter;
}
}
参考地址:http://answers.unity3d.com/questions/392606/line-drawing-how-can-i-interpolate-between-points.html