0

Does anyone have any suggestions to create an interpolating spline curve. I'm trying to develop a game in opengl and I can't get the objects to follow a curve. The function should go something like.....

void interpolatePath(Vec3d startPos, Vec3d targetPos, float u, Vec3d &interpPos)

The object starts at a position and the user clicks and the object moves to that point. I have it now so that the object goes in a straight line, but I want it to follow a curve.

Straight line code in above funciton:

//interpPos.x = (u)*targetPos.x+(1-u)*startPos.x;
  //interpPos.y = (u)*targetPos.y+(1-u)*startPos.y;
  //interpPos.z = (u)*targetPos.z+(1-u)*startPos.z;

Would a bezier curve work? How would I implement it?

[x,y]=(1–t)^3P0+3(1–t)^2tP1+3(1–t)t^2P2+t^3P3

Thank you

user2855460
  • 1
  • 1
  • 4
  • You can certainly have it follow a bezier path, but you need to define which path between the 2 points it should follow. There are an infinite number of bezier curves that fit between any 2 points. Are there obstacles between the two points that it needs to avoid? – user1118321 Oct 31 '13 at 04:26
  • I agree with user1118321. In your case `startPos` is `P0` and `targetPos` is `P3`, however, cubic Bezier spline requires also control points `P1` and `P2` to define the curve. For quadratic Bezier you will need only one extra point and what you have now is a linear Bezier spline. – divanov Nov 08 '13 at 18:50
  • see [SVG Paths and the Catmull-Rom algorithm](http://stackoverflow.com/a/30750626/2521214) – Spektre Nov 11 '15 at 13:34

1 Answers1

1

You can use B-Spline for interpolating given set of points in which 3 points should be required for polynomial or cubic interpolation. If not it should be a linear interpolation. Here I will give you an example using Eigen lib for B-Spline interpolation.

#include <Eigen/Core>
#include <unsupported/Eigen/Splines>


typedef Eigen::Spline<float, 3> Spline3d;

int main(){
  std::vector<Eigen::VectorXf> waypoints;
  Eigen::Vector3f po1(2,3,4);
  Eigen::Vector3f po2(2,5,4);
  Eigen::Vector3f po3(2,8,9);
  Eigen::Vector3f po4(2,8,23);
  waypoints.push_back(po1);
  waypoints.push_back(po2);
  waypoints.push_back(po3);
  waypoints.push_back(po4);

  // The degree of the interpolating spline needs to be one less than the number of points
  // that are fitted to the spline.
  Eigen::MatrixXf points(3, waypoints.size());
  int row_index = 0;
  for(auto const way_point : waypoints){
      points.col(row_index) << way_point[0], way_point[1], way_point[2];
      row_index++;
  }
  Spline3d spline = Eigen::SplineFitting<Spline3d>::Interpolate(points, 2);
  float time_ = 0;
  for(int i=0; i<20; i++){
      time_ += 1.0/(20*1.0);
      Eigen::VectorXf values = spline(time_);
      std::cout<< values << std::endl;
  }
  return 0;
}
GPrathap
  • 7,336
  • 7
  • 65
  • 83