C++ 中的插值样条曲线

interpolating spline curve in c++

本文关键字:样条曲线 插值 C++      更新时间:2023-10-16

有人对创建插值样条曲线有任何建议吗?我正在尝试在opengl中开发一个游戏,但我无法让对象遵循曲线。该函数应该类似于.....

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

从一个位置开始,用户单击,对象移动到该点。我现在有了它,以便对象沿直线移动,但我希望它遵循曲线。

上述功能中的直线代码:

//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;

贝塞尔曲线会起作用吗?我将如何实现它?

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

(1–t)t^2P2+t^3P3

谢谢

您可以使用 B 样条对给定的点集进行插值,其中多项式或三次插值需要 3 个点。如果不是,则应该是线性插值。在这里,我将给你一个使用 Eigen lib 进行 B 样条插值的示例。

#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;
}