在3D中,我们可以通过在Bezier曲线上添加法线来使曲线看起来更加真实。下面是一些示例代码,可以在Unity引擎中使用:
public class BezierCurve : MonoBehaviour
{
public Transform[] controlPoints;
private Vector3[] positions;
private Vector3[] normals;
private int segments = 50;
private Mesh mesh;
private void Start()
{
mesh = new Mesh();
GetComponent().mesh = mesh;
positions = new Vector3[controlPoints.Length];
normals = new Vector3[controlPoints.Length];
for (int i = 0; i < controlPoints.Length; i++)
{
positions[i] = controlPoints[i].position;
}
CalculateNormals();
CreateCurve();
}
private void CalculateNormals()
{
normals[0] = ((positions[1] - positions[0]) + (positions[2] - positions[0])).normalized;
for (int i = 1; i < normals.Length - 1; i++)
{
normals[i] = ((positions[i + 1] - positions[i - 1]) + (positions[i + 2] - positions[i])).normalized;
}
normals[normals.Length - 1] = ((positions[normals.Length - 2] - positions[normals.Length - 1]) + (positions[normals.Length - 3] - positions[normals.Length - 1])).normalized;
}
private void CreateCurve()
{
Vector3[] vertices = new Vector3[segments * (controlPoints.Length - 1)];
Vector3[] n = new Vector3[segments * (controlPoints.Length - 1)];
int[] triangles = new int[(segments - 1) * 6 * (controlPoints.Length - 2)];
int triIndex = 0;
for (int i = 0; i < controlPoints.Length - 1; i++)
{
for (int j = 0; j < segments; j++)
{
float t = j / (float)segments;
int vertexIndex = i * segments + j;
vertices[vertexIndex