简体   繁体   English

使用方向向量和变换矩阵的OpenGL对象旋转

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

I have a physics simulator which has a direction vector and I need to calculate the rotation of the object to follow it. 我有一个物理模拟器,它具有方向矢量,我需要计算对象的旋转以跟随它。

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

The object seems to rotate in the right direction but is only drawn in one axis (looks like a 2D object and cant be seen from the x axis when at the origin). 该对象似乎在向右旋转,但仅沿一个轴绘制(看起来像2D对象,在原点处无法从x轴看到)。 I don't know if this is more to do with how OpenGL works? 我不知道这与OpenGL如何工作有关吗?

This doesn't look right. 这看起来不对。 You have variables named crossproduct , but you're not calculating a cross product anywhere. 您有名为crossproduct变量,但您没有在任何地方计算叉积。 I think this could fundamentally work if you replace your vector operations by cross products where the name indicates that they should be. 我认为,如果您将交叉运算替换为交叉乘积,而交叉乘积的名称表示应使用交叉乘积,则此方法从根本上可行。

Also, it looks like you're partly not using the right variable names. 另外,看起来您在某种程度上没有使用正确的变量名。 For example, there are values assigned to up_vector and direction_vector , but then the calculations use up and direction . 例如,有分配给up_vectordirection_vector值,但随后计算使用updirection

Using your initial naming, this would become: 使用您的初始命名,它将变成:

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

Then build the matrix with those vectors as before. 然后像以前一样用这些向量构建矩阵。 Of course this goes wrong if direction_vector is pointing exactly in the same direction as up_vector . 当然,如果direction_vector指向的方向与up_vector完全相同,这是错误的。 To make this robust for all directions, you'll have to special case that. 为了使它在所有方向上都健壮,您必须对此进行特殊处理。

In the above, crossProduct() is a standard cross product: 在上面, 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