最近为了模拟法术的运行轨迹,打算使用了贝塞尔曲线,以前在 2D 开发项目中也经常使用贝塞尔曲线,但是在 3D 场景中贝塞尔曲线的实现还是稍稍有些麻烦,于是在网上收集 Unity3D 贝塞尔曲线的代码,原文链接:http://www.xuanyusong.com/archives/1548
Demo 过程如下:
![](http://www.omuying.com/Images/Upload/Article/image/20140930/20140930135830_4062.jpg)
![](http://www.omuying.com/Images/Upload/Article/image/20140930/20140930135842_1562.jpg)
示例代码:
02 | using System.Collections; |
04 | public class BezierPath : MonoBehaviour |
06 | public GameObject sphere; |
08 | public GameObject begin; |
09 | public GameObject control0; |
10 | public GameObject control1; |
11 | public GameObject end; |
15 | Bezier bezier = new Bezier (begin.transform.position, control0.transform.position, control1.transform.position, end.transform.position); |
18 | Vector3[] resultList = new Vector3[pointSize]; |
20 | for ( int index = 1; index <= pointSize; index ++) |
22 | resultList[index - 1] = bezier.GetPointAtTime(( float )index / ( float )pointSize); |
25 | foreach (Vector3 point in resultList) |
27 | GameObject gameObject = (GameObject)Instantiate(sphere); |
28 | gameObject.transform.localPosition = point; |
29 | gameObject.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); |
Bezier.cs
10 | private Vector3 b0 = Vector3.zero; |
11 | private Vector3 b1 = Vector3.zero; |
12 | private Vector3 b2 = Vector3.zero; |
13 | private Vector3 b3 = Vector3.zero; |
30 | /// <param name="v0">起始点</param> |
31 | /// <param name="v1">第一个控制点</param> |
32 | /// <param name="v2">第二个控制点(通过可省略,有 Vector3.Zero 代码)</param> |
33 | /// <param name="v3">结束点</param> |
34 | public Bezier( Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3 ) |
45 | /// <returns>The point at time.</returns> |
46 | /// <param name="t">t 的取值范围在 0.0 >= t <= 1.0</param> |
47 | public Vector3 GetPointAtTime( float t ) |
53 | float x = this .Ax * t3 + this .Bx * t2 + this .Cx * t + p0.x; |
54 | float y = this .Ay * t3 + this .By * t2 + this .Cy * t + p0.y; |
55 | float z = this .Az * t3 + this .Bz * t2 + this .Cz * t + p0.z; |
56 | return new Vector3( x, y, z ); |
59 | private void SetConstant() |
61 | this .Cx = 3f * ( ( this .p0.x + this .p1.x ) - this .p0.x ); |
62 | this .Bx = 3f * ( ( this .p3.x + this .p2.x ) - ( this .p0.x + this .p1.x ) ) - this .Cx; |
63 | this .Ax = this .p3.x - this .p0.x - this .Cx - this .Bx; |
64 | this .Cy = 3f * ( ( this .p0.y + this .p1.y ) - this .p0.y ); |
65 | this .By = 3f * ( ( this .p3.y + this .p2.y ) - ( this .p0.y + this .p1.y ) ) - this .Cy; |
66 | this .Ay = this .p3.y - this .p0.y - this .Cy - this .By; |
67 | this .Cz = 3f * ( ( this .p0.z + this .p1.z ) - this .p0.z ); |
68 | this .Bz = 3f * ( ( this .p3.z + this .p2.z ) - ( this .p0.z + this .p1.z ) ) - this .Cz; |
69 | this .Az = this .p3.z - this .p0.z - this .Cz - this .Bz; |
72 | private void CheckConstant() |
74 | if ( this .p0 != this .b0 || this .p1 != this .b1 || this .p2 != this .b2 || this .p3 != this .b3 ) |