Hello!
I have a problem with implementing of cubic Hermite spline. I need to move my gameobject towards by spline. I found Hermite spline definition on Wiki Cubic Hermite spline - Wikipedia and implemented it in the scripts below. When my gameobject moves through the control point it jumps a little. I suggest that the problem is the difference between derivatives before and after that point.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spline {
public Vector3[] points, derivatives;
private int fragmentIndex = 0;
private float t = 0f;
public void ConfigSpline(Vector3 derivativeAt0){
derivatives = new Vector3[points.Length];
float sum = 0;
derivatives[0] = derivativeAt0;
for (int i = 1; i < derivatives.Length - 1; i++) {
/*[i] = (points[i+1] - points[i-1])/
((points[i-1]-points[i+1]).magnitude);*/
derivatives [i] = (points [i + 1] - points [i]) / (2 * (points [i + 1] - points [i]).magnitude) +
(points [i] - points [i - 1]) / (2 * (points [i] - points [i - 1]).magnitude);
sum += (points [i - 1] - points [i]).magnitude;
}
derivatives[derivatives.Length - 1] = (points[derivatives.Length - 1] - points[0])/
(sum + (points[derivatives.Length - 1] - points[derivatives.Length - 2]).magnitude);
}
public Vector3 GetPoint(float dt){
t += dt;
if (t > 1f) {
t -= 1.0f;
fragmentIndex++;
if (fragmentIndex == points.Length)
//TODO
;
}
return (2 * Mathf.Pow (t, 3) - 3 * Mathf.Pow (t, 2) + 1) * points [fragmentIndex] +
(Mathf.Pow (t, 3) - 2 * Mathf.Pow (t, 2) + t) * (points [fragmentIndex + 1] - points [fragmentIndex]).magnitude * derivatives [fragmentIndex] +
(-2 * Mathf.Pow (t, 3) + 3 * Mathf.Pow (t, 2)) * points [fragmentIndex + 1] +
(Mathf.Pow (t, 3) - Mathf.Pow (t, 2)) * (points [fragmentIndex + 1] - points [fragmentIndex]).magnitude * derivatives [fragmentIndex + 1];
}
public void Reset () {
fragmentIndex = 0;
t = 0f;
}
}
This spline is used in that method:
private void MoveTowardsByPath () {
originTrajectory.transform.position = spline.GetPoint (Time.deltaTime);
originTrajectory.transform.rotation = Quaternion.LookRotation (moveDirection);
transform.rotation = originTrajectory.transform.rotation;
transform.position = originTrajectory.transform.position;
moveDirection = transform.position - lastPosition;
lastPosition = transform.position;
}