I am trying to implement the formula for bezier curves of Nth order in my program. It looks to me that I have done everything right but the visual result is not correct.
Here it is:
The red cube is P0 and the blue is P8. The white cubes are the actual set of points that make the curve. The orange cubes are the control points.
What I see is that there is a loop before the end of the curve where the curve attaches to the last (blue cube) point. Looks like there is an invisible point. And another thing is that between P0 and P1 is also something weird going on...
Can anyone help me to resolve it?
Here is the code I use:
private void Update()
{
controlPointsCoords = ControlPoints.Select(p => p.transform.position).ToArray();
for (int p = 0; p < PointsSet.Count; p++)
{
PointsSet[p].transform.position = CurveDegreeN
(
controlPointsCoords,
Rt(p, PointsSet.Count)
);
}
}
private Vector3 CurveDegreeN(Vector3[] pointsCoords, float u)
{
float X = 0, Y = 0, Z = 0;
float n = pointsCoords.Length - 1;
for (int i = 0; i < pointsCoords.Length; i++)
{
var coef = (Factorial(n) / (Factorial((float)i) * Factorial(n - i))) * Mathf.Pow(u, i) * Mathf.Pow(1 - u, n - i);
X += coef * pointsCoords[i].x;
Y += coef * pointsCoords[i].y;
Z += coef * pointsCoords[i].z;
}
return new Vector3(X, Y, Z);
}
private float Factorial(float n)
{
if (n == 0) return 1;
float res = 0.0f;
for (int i = 1; i < n; i++) res += (float)Math.Log(i);
return (float)Math.Exp(res);
}
private float Rt(int current, int count)
{
return ((float)current - 0) / ((float)count - 0) * (1 - 0) + 0;
}
I hope this will be clear for someone! Thank you in advance!
UPDATE: I reduced amount of points to 3. Here is the result: 3 Points curve. It is clearly visible here that something is wrong with the computations... Any more suggestions?