C++/openGL : Rotating a QUAD toward a point using quaternions

标签 c++ opengl rotation quaternions

当我在某个位置有一个 QUAD 时,如何旋转它使其法线指向给定点?想象一下彩色 block 只是矩形四边形,那么这张图片有点表达我的意思。四边形都以指向球体中心的方式定向。

alt text http://emrahgunduz.com/wp-content/uploads/2009/01/material_id_gui-600x364.jpg

也许第二张图片显示了更多我正在尝试做的事情: alt text http://img689.imageshack.us/img689/3130/screenshot20100708at555.png

我正在使用 openGL/C++(和 Eigen 库)。我有这段代码来绘制一个简单的四边形:

#include "ofMain.h"
#include "Quad.h"
Quad::Quad(Vector3f oPosition):position(oPosition) {
}

void Quad::update() {
}

void Quad::draw() {
    float size = 1.3;
    glColor3f(1.0f, 0.0f, 0.6f);
    glPushMatrix();
        glTranslatef(position.x(), position.y(), position.z());
        glScalef(size, size,size);
        glBegin(GL_QUADS);
            glVertex3f(0,0,0);
            glVertex3f(1,0,0);
            glVertex3f(1,1,0);
            glVertex3f(0,1,0);
        glEnd();
    glPopMatrix();
}

更新 17-07 亲爱的读者,

只是在旋转四边形方面走得更远了一点。我随机放置了几个四边形,然后使用以下回复中的描述使用此代码将它们旋转到 look_at vector3f:

void Quad::draw() {
    float size = 0.5;
    glColor3f(1.0f, 0.0f, 0.6f);
    glPushMatrix();
        Vector3f center = look_at - position;
        Vector3f center_norm = center.normalized();
        float r_angle   = acos(center_norm.dot(normal));
        Vector3f axis = normal.normalized().cross(center_norm);

        glPointSize(8);
        glLineWidth(4.0f);

        // draw the center point
        glColor3f(1.0f, 0.0f, 0.0f);
        glBegin(GL_POINTS); 
            glVertex3fv(look_at.data());
        glEnd();

        // draw the quad
        glColor4f(0.0f, 0.0f, 0.0f, 0.85f); 
        glTranslatef(position.x(), position.y(), position.z());
        glRotatef(r_angle * RAD_TO_DEG, axis.x(), axis.y(), axis.z());
        glScalef(size, size,size);
        glBegin(GL_QUADS);
            glVertex3f(-0.5,-0.5,0);
            glVertex3f(0.5,-0.5,0);
            glVertex3f(0.5,0.5,0);
            glVertex3f(-0.5,0.5,0);
        glEnd();

    glPopMatrix();
}

结果是这样的: alt text

如您所见,我已经快完成了,尽管四边形的旋转仍然有点“奇怪”。我看到下面带有彩色四边形的图像,您可以清楚地看到旋转的差异。我怎样才能以这样的方式旋转四边形以获得与下面彩色球体相同的结果?

最佳答案

旋转轴 = normalize(crossproduct(currentNormal, desiredNormal))

旋转角度 = acos(dotproduct(normalize(currentNormal), normalize(desiredNormal)).

您可以根据轴和角度构建旋转矩阵或四元数。可以在任何有关四元数的资源中找到确切的公式。

您可能需要翻转角度或轴,具体取决于您是围绕其底部还是围绕其尖端旋转。

还有 THIS资源似乎有足够的关于四元数、旋转和一般 3d 空间的信息。

关于C++/openGL : Rotating a QUAD toward a point using quaternions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3204001/

相关文章:

rotation - 三个J,改变旋转点

c++ - 防止通过派生类调用基类中的静态方法?

c++ - const 指针成员和 operator=

c - glPolygonOffset() 不适用于对象轮廓

java - 使用 OpenGL/LWJGL 通过 glDrawArrays 绘制 VBO 时出现问题

iphone - UIImage 旋转时质量下降

c++ Armadillo 转换/转换为整数类型 vector 或矩阵

c++ - 如何通过宏检查是否使用了 GNU libstdc++?

c - glewGetString(GLEW_VERSION) 和 glewIsSupported 之间的区别

c++ - OpenGL - 旋转播放器位置以面对鼠标指针