public static Vector3 GetPointOnCubicCurve(float time, Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent) { float t = time; float u = 1f - t; float t2 = t * t; float u2 = u * u; float u3 = u2 * u; float t3 = t2 * t; Vector3 result = (u3) * startPosition + (3f * u2 * t) * startTangent + (3f * u * t2) * endTangent + (t3) * endPosition; return result; }
/// <summary> /// Add a key point at a specified index /// </summary> /// <param name="index">The index at which the key point will be added</param> /// <returns>The new key point</returns> public BezierPoint3D AddKeyPointAt(int index) { BezierPoint3D newPoint = new GameObject("Point " + this.KeyPoints.Count, typeof(BezierPoint3D)).GetComponent <BezierPoint3D>(); newPoint.Curve = this; newPoint.transform.parent = this.transform; newPoint.transform.localRotation = Quaternion.identity; if (this.KeyPointsCount == 0 || this.KeyPointsCount == 1) { newPoint.LocalPosition = Vector3.zero; } else { if (index == 0) { newPoint.Position = (this.KeyPoints[0].Position - this.KeyPoints[1].Position).normalized + this.KeyPoints[0].Position; } else if (index == this.KeyPointsCount) { newPoint.Position = (this.KeyPoints[index - 1].Position - this.KeyPoints[index - 2].Position).normalized + this.KeyPoints[index - 1].Position; } else { newPoint.Position = BezierCurve3D.GetPointOnCubicCurve(0.5f, this.KeyPoints[index - 1], this.KeyPoints[index]); } } this.KeyPoints.Insert(index, newPoint); return(newPoint); }