前言
通过贝塞尔曲线得到了多组曲线,现在需要在曲线上绘制一条轨道出来。
思路
曲线上的节点做叉乘计算。
第一个节点计算与后一个节点的叉乘
中间的节点计算上一个节点的叉乘和下一个节点的叉乘然后做均值处理
最后一个节点与上一个节点做叉乘
效果如下:
Mesh网格绘制
核心代码如下:
public class LineMeshCreater : MonoBehaviour
{
public Mesh GetMesh(Vector3[] posarray, float width , Vector3 world, Vector3 nextNode = default)
{
Mesh mesh = new Mesh();
DrawMesh(mesh, posarray, width , world , nextNode);
return mesh;
}
/// <summary>
/// 绘制Mesh
/// </summary>
/// <param name="mesh"></param>
/// <param name="posarray"></param>
/// <param name="width"></param>
public void DrawMesh(Mesh mesh, Vector3[] posarray, float width, Vector3 world, Vector3 nextNode = default)
{
mesh.Clear();
mesh.vertices = getVertices(posarray, width , world , nextNode);
mesh.triangles = getTriangles(mesh.vertexCount);
mesh.RecalculateNormals();
}
/// <summary>
/// 顶点计算
/// </summary>
/// <returns></returns>
Vector3[] getVertices(Vector3[] posarray, float width , Vector3 world , Vector3 nextNode = default)
{
Vector3[] vector3s = new Vector3[posarray.Length * 2];
for (int i = 0; i < posarray.Length; i++)
{
Vector3 reght = Vector3.zero;
if (i > 0 && i < posarray.Length - 1)
{
Vector3 t_l, t_r;
t_l = t_r = Vector3.zero;
//节点左边的叉乘向量
getCross(posarray[i - 1] - posarray[i], world, ref t_l);
//节点右边的叉乘向量
getCross(posarray[i + 1] - posarray[i], world, ref t_r);
//取均值
t_r = -t_r;
reght = (t_r + t_l) / 2;
}
else if (i == posarray.Length - 1)
{
if (nextNode != Vector3.zero)
{
//到下一个节点的叉乘向量
getCross(nextNode - posarray[i], world, ref reght);
reght = -reght;
}
else {
//节点左边的叉乘向量
getCross(posarray[i - 1] - posarray[i], world, ref reght);
}
}
else
{
//节点右边的叉乘向量
getCross(posarray[i + 1] - posarray[i], world, ref reght);
reght = -reght;
}
//右顶点
vector3s[i * 2] = reght * (width / 2) + posarray[i] - posarray[0];
//左顶点
vector3s[i * 2 + 1] = -reght * (width / 2) + posarray[i] - posarray[0];
//Debug.DrawLine(vector3s[i * 2] + posarray[0], vector3s[i * 2 + 1] + posarray[0], Color.red);
}
return vector3s;
}
/// <summary>
/// 叉乘
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="vector"></param>
void getCross(Vector3 a, Vector3 b, ref Vector3 vector)
{
vector = new Vector3(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x
).normalized;
}
/// <summary>
/// 三角面计算
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
int[] getTriangles(int count)
{
List<int> vector3s = new List<int>();
for (int i = 0; i < count - 2; i += 2)
{
//右下三角面
int p0, p1, p2;
p0 = i;
p1 = i + 1;
p2 = i + 2;
vector3s.Add(p0);
vector3s.Add(p1);
vector3s.Add(p2);
//左上三角面
p0 = i + 1;
p1 = i + 3;
p2 = i + 2;
vector3s.Add(p0);
vector3s.Add(p1);
vector3s.Add(p2);
}
return vector3s.ToArray();
}
}
另外有一点需要注意,每一组曲线节点最后一个节点和下一组的第二个节点要做一次叉乘,这样可以完美拼接,不会出现缝隙。
在贝塞尔曲线中设置一个细分值,可以使实际轨迹更加平滑,效果如下:
网友评论