Hi.
I’m working on implementing catmull rom curve interpolation in Unity for a class.
I have a scene with a camera and a sphere with a .cs script attached.
When I run the scene, my script generates a number of control points, which the sphere will transform towards. The problem I am having is that after my sphere reaches the second control point, it continues in that direction infinitely. I would like the sphere to transform towards the next control point.
using UnityEngine;
using System.Collections;
public class CatmullRomCurveInterpolation : MonoBehaviour {
const int NumberOfPoints = 8;
Vector3[] controlPoints;
public float speed = 1f;
const int MinX = -5;
const int MinY = -5;
const int MinZ = 0;
const int MaxX = 5;
const int MaxY = 5;
const int MaxZ = 5;
float time =0;
const float DT= 0.01f;
/* Returns a point on a cubic Catmull-Rom/Blended Parabolas curve
* u is a scalar value from 0 to 1
* segment_number indicates which 4 points to use for interpolation
*/
Vector3 ComputePointOnCatmullRomCurve(float u, int segmentNumber)
{
Vector3 point = new Vector3();
Vector3 a = controlPoints[segmentNumber];
Vector3 b = controlPoints[segmentNumber+1];
Vector3 c = controlPoints[segmentNumber+2];
Vector3 d = controlPoints[segmentNumber+3];
point = ((-0.5f*a + 1.5f*b - 1.5f*c + 0.5f*d) * (u * u * u)
+ (1f*a - 2.5f*b + 2f*c - 0.5f*d) * (u * u)
+ (-0.5f*a + 0.5f*c) * u
+ 1f*b);
Debug.Log("POINT: "+point);
return point;
}
void GenerateControlPointGeometry()
{
for(int i = 0; i < NumberOfPoints; i++)
{
GameObject tempcube = GameObject.CreatePrimitive(PrimitiveType.Cube);
tempcube.transform.localScale -= new Vector3(0.8f,0.8f,0.8f);
tempcube.transform.position = controlPoints*;*
-
} *
-
}*
-
// Use this for initialization*
-
void Start () {*
-
controlPoints = new Vector3[NumberOfPoints];*
-
// set points randomly...*
-
controlPoints[0] = new Vector3(0,0,0);*
-
for(int i = 1; i < NumberOfPoints; i++)*
-
{*
_ controlPoints = new Vector3(Random.Range(MinX,MaxX),Random.Range(MinY,MaxY),Random.Range(MinZ,MaxZ));_
* }*
_ /…or hard code them for testing_
_ controlPoints[0] = new Vector3(0,0,0);_
_ controlPoints[1] = new Vector3(0,0,0);_
_ controlPoints[2] = new Vector3(0,0,0);_
_ controlPoints[3] = new Vector3(0,0,0);_
_ controlPoints[4] = new Vector3(0,0,0);_
_ controlPoints[5] = new Vector3(0,0,0);_
_ controlPoints[6] = new Vector3(0,0,0);_
_ controlPoints[7] = new Vector3(0,0,0);*_
_ */_
* GenerateControlPointGeometry();*
* }*
* // Update is called once per frame*
* void Update () {*
* int segmentNumber=0;*
* //foreach (Vector3 i in controlPoints) {*
* for(int i=0; i<NumberOfPoints-3; i++) { *
* time += DT;*
* // TODO - use time to determine values for u and segment_number in this function call*
* Vector3 temp = ComputePointOnCatmullRomCurve(time/2, segmentNumber);*
* transform.position = temp;*
* segmentNumber++;*
* Debug.Log("SEGMENTNUMBER: "+segmentNumber);*
* }*
* }*
}