Last Updated January 21, 2009
The XNA Vector3 class provides a CatmullRom method to generate points on a Catmull-Rom curve. The function takes the 4 control points (Vector3) and a scalar between 0 & 1, indicating how far along the interval between the central control points we need.
e.g.
v=Vector3.CatmullRom(p1, p2, p3, p4,0.25); //returns a point on the curve, at 25% of the distance between p2 & p3
The following code segment, adapted from the book Professional
XNA Game Programming,
shows how to convert an list of control points (unlimited control points permitted,
minimum 4), into a list of points which can be used to build a Catmull-rom curve;
void GetTrackPoints()
{
for (int num = 0; num < inputpoints.Count; num++)
{
// Get the 4 required points for the catmull rom spline
Vector3 p1 = inputpoints[num - 1 < 0 ? inputpoints.Count - 1 : num - 1];
Vector3 p2 = inputpoints[num];
Vector3 p3 = inputpoints[(num + 1) % inputpoints.Count];
Vector3 p4 = inputpoints[(num + 2) % inputpoints.Count];
// Calculate number of iterations we use here based
// on the distance of the 2 points we generate new points from.
float distance = Vector3.Distance(p2, p3);
int numberOfIterations =
(int)(segmentsPer100Meters * (distance / 100.0f));
if (numberOfIterations <= 0)
numberOfIterations = 1;
for (int iter = 0; iter < numberOfIterations; iter++)
{
Vector3 newVertex = Vector3.CatmullRom(p1, p2, p3, p4, iter / (float)numberOfIterations);
points.Add(newVertex);
} // for (iter)
} // for (num)
}
© Ken Power 2010