Unity贝塞尔曲线: Unity-BezierCurves
程序员文章站
2024-01-16 21:37:16
...
前言
假设我们现在要做一个 “鱼按照编辑好的路径进行游动” 的功能。
这个时候,我们需要有一个曲线编辑的功能。
推荐使用贝塞尔曲线来实现,github上已经有人做好了这样的插件。
Unity-BezierCurves插件
创建曲线
菜单: GameObjects -> Create Other -> Bezier Curve
代码例子:
BezierCurve3D curve = GetComponent<BezierCurve3D>();
// Evaluate a position and rotation along the curve at a given time
float time = 0.5f; // In range [0, 1]
Vector3 position = curve.GetPoint(time);
Quaterion rotation = curve.GetRotation(time, Vector3.up);
// Get the length of the curve
// This operation is not very heavy, but I advise you to cache the length if you are going to use it
// many times and when you know that the curve won't change at runtime.
float length = curve.GetApproximateLength();
// Other methods
Vector3 tangent = curve.GetTangent(time);
Vector3 binormal = curve.GetBinormal(time, Vector3.up);
Vector3 normal = curve.GetNormal(time, Vector3.up);
// Add a key point at the end of the curve
BezierPoint3D keyPoint = curve.AddKeyPoint(); // via fast method
BezierPoint3D keyPoint = curve.AddKeyPointAt(curve.KeyPointsCount); // via specific index
// Remove a key point
bool isRemoved = curve.RemoveKeyPointAt(0); // Remove the first key point
// Foreach all key points
for (int i = 0; i < curve.KeyPointsCount; i++)
{
Debug.Log(curve.KeyPoints[i].Position);
Debug.Log(curve.KeyPoints[i].LeftHandleLocalPosition);
Debug.Log(curve.KeyPoints[i].RightHandleLocalPosition);
}
改进的地方
上面的插件是按预设的方式保存路径资源的,这个其实有点浪费空间,我们可以自己做二进制序列化和反序列化
比如我们正真需要的数据是:
Sampling
Normalized Time
每个点的Handle Type,中心坐标,左手柄坐标,右手柄坐标
把这些数据按一定的顺序写到二进制文件中,读取的时候,再按写入时的顺序读取出来,然后构建成BezierCurve3D对象,这样就可以使用GetPoint和GetRotation等接口了