簡體   English   中英

使用方向向量和變換矩陣的OpenGL對象旋轉

[英]OpenGL object rotations using a direction vector and transformation matrix

我有一個物理模擬器,它具有方向矢量,我需要計算對象的旋轉以跟隨它。

     Vec3f up_vector = Vec3f(0,1,0);
     Vec3f direction_vector  = directionVector(position, previous_position);
     Vec3f crossproduct = normaliseVector(Vec3f(up[0] * direction[0], up[1] * direction[1], up[2] * direction[2]));
      Vec3f crossproduct2 = normaliseVector(Vec3f(crossproduct[0] * direction_vector[0], crossproduct[1] * direction_vector[1], crossproduct[2] * direction_vector[2]));

        rotation = Matrix44f(
        { crossproduct[0], crossproduct[1], crossproduct[2], 0 },
        { crossproduct2[0], crossproduct2[1], crossproduct2[2], 0 },
        { direction_vector[0], direction_vector[1], direction_vector[2], 0 },
        { 0, 0, 0, 1 });

        glMultMatrixf(rotation);

該對象似乎在向右旋轉,但僅沿一個軸繪制(看起來像2D對象,在原點處無法從x軸看到)。 我不知道這與OpenGL如何工作有關嗎?

這看起來不對。 您有名為crossproduct變量,但您沒有在任何地方計算叉積。 我認為,如果您將交叉運算替換為交叉乘積,而交叉乘積的名稱表示應使用交叉乘積,則此方法從根本上可行。

另外,看起來您在某種程度上沒有使用正確的變量名。 例如,有分配給up_vectordirection_vector值,但隨后計算使用updirection

使用您的初始命名,它將變成:

Vec3f up_vector = Vec3f(0,1,0);
Vec3f direction_vector  = directionVector(position, previous_position);
// Assuming that directionVector() returns a normalized vector.
Vec3f crossproduct = normaliseVector(crossProduct(up_vector, direction_vector));
Vec3f crossproduct2 = crossProduct(direction_vector, crossproduct);

然后像以前一樣用這些向量構建矩陣。 當然,如果direction_vector指向的方向與up_vector完全相同,這是錯誤的。 為了使它在所有方向上都健壯,您必須對此進行特殊處理。

在上面, crossProduct()是標准的叉積:

Vec3f crossProduct(const Vec3f& v1, const Vec3f& v2) {
    return Vec3f(v1.y * v2.z - v1.z * v2.y,
                 v1.z * v2.x - v1.x * v2.z,
                 v1.x * v2.y - v1.y * v2.x);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM