2010-12-19 18 views
2

我在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

第一個問題:
如果您跟蹤對象的先前的位置以及新的位置,你可以找出相對方向沒有找到樣條曲線的切線,像這樣:

facing = newPosition - previousPosition 

第二個問題:
您可以使用這裏所描述的旋轉物體面對一個特定方向的答案:What is the easiest way to align the Z axis with a vector?

+0

謝謝你的裏NK。我沒有找到。你對找到切線的建議是可以的,但它不太理想,因爲在計算旋轉之前你必須計算出移動。 – 2010-12-21 04:01:30

+0

爲什麼旋轉之前的移動出現問題?你是否希望首先旋轉,然後翻譯物體的正面方向? – 2010-12-21 06:59:39

相關問題