我在OpenGL中沿着样条线路径设置对象动画。我正在使用一些代码来生成样条曲线。可悲的是,我还不了解它的机制。我希望我的对象对齐以匹配路径的切线,使其看起来像跟随路径。
两个问题 如何在给定点找到与路径相切的矢量? 其次,假设向量和向上的向量,如何旋转对象以对齐?
这是我的样条代码。
public Spline(Vector Path[])
{
ControlPoints = Path;
// Flatten out the control points array.
int len = ControlPoints.length;
float[] controlsX = new float[len];
float[] controlsY = new float[len];
float[] controlsZ = new float[len];
for (int i = 0; i < len; ++i)
{
controlsX[i] = ControlPoints[i].x;
controlsY[i] = ControlPoints[i].y;
controlsZ[i] = ControlPoints[i].z;
}
// Calculate the gamma values just once.
final int n = ControlPoints.length - 1;
float[] gamma = new float[n + 1];
gamma[0] = 1.0f / 2.0f;
for (int i = 1; i < n; ++i) gamma[i] = 1 / (4 - gamma[i - 1]);
gamma[n] = 1 / (2 - gamma[n - 1]);
// Calculate the cubic segments.
cubicX = calcNaturalCubic(n, controlsX, gamma);
cubicY = calcNaturalCubic(n, controlsY, gamma);
cubicZ = calcNaturalCubic(n, controlsZ, gamma);
}
private Cubic[] calcNaturalCubic(int n, float[] x, float[] gamma)
{
float[] delta = new float[n + 1];
delta[0] = 3 * (x[1] - x[0]) * gamma[0];
for (int i = 1; i < n; ++i)
{
delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i];
}
delta[n] = (3 * (x[n] - x[n - 1])-delta[n - 1]) * gamma[n];
float[] D = new float[n + 1];
D[n] = delta[n];
for (int i = n - 1; i >= 0; --i)
{
D[i] = delta[i] - gamma[i] * D[i + 1];
}
// Calculate the cubic segments.
Cubic[] C = new Cubic[n];
for (int i = 0; i < n; i++) {
final float a = x[i];
final float b = D[i];
final float c = 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1];
final float d = 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1];
C[i] = new Cubic(a, b, c, d);
}
return C;
}
final public Vector GetPoint(float Position)
{
if(Position >= 1) { return ControlPoints[ControlPoints.length - 1]; }
float position = Position * cubicX.length;
int splineIndex = (int)Math.floor(position);
float splinePosition = position - splineIndex;
return new Vector(cubicX[splineIndex].eval(splinePosition), cubicY[splineIndex].eval(splinePosition), cubicZ[splineIndex].eval(splinePosition));
}
答案 0 :(得分:0)
第一个问题:
如果您跟踪对象的先前位置以及新位置,则可以找到面向方向而不查找样条曲线的切线,如下所示:
facing = newPosition - previousPosition
第二个问题:
您可以使用此处描述的答案来旋转对象以面向特定方向:What is the easiest way to align the Z axis with a vector?