使用 OpenGL 在圆圈中移动对象?

Move Object in Circle using OpenGL?

我有一个对象,我想在 Open GL/Visual Studio 中绕圈移动。但到目前为止,该对象只是围绕自身旋转。

如何让它做圆周运动?

目前,它只是立即平移对象,而不是在我的旋转动画过程中。

这是我在显示函数中的代码 - 因为我被告知如果您希望对象不围绕自身旋转,则需要进行平移。但是到目前为止,我的对象只是完全忽略了这里的翻译,仍然围绕着自己旋转..

glRotatef(0.0f, 0, 1, 0);
glTranslatef(2.0, 0.0, 0.0);
glRotatef(angle, 0.0, -1.0, 0.0);   

drawExcavator(); // draws the object

这是我的动画函数,用于稍后定义我在 glRotatef 调用中使用的角度:

void animate() {

    // calculating the time needed for the animation 
    static long time = clock();
    long oldTime = time;
    float diffTime;
    time = clock();
    diffTime = ((float)(time - oldTime)) / ((float)CLOCKS_PER_SEC); // taken from the exercise sheets

    // checking if the animation has not been stopped:
    if (!pause) {
        angle += diffTime*rotateSpeed;
        elapsedTime += diffTime;
        frameCount++;

        // adding up the frames so that they are shown in the window:
        if (elapsedTime > 1.0)
        {
            // counting the fps so that they are outprinted in the window line:
            fps = (float)frameCount / elapsedTime;
            fps = fps / 100; // for correct frame numbers 
            elapsedTime = 0.0;
            frameCount = 0.0;
        }
    }
}

你必须交换平移和旋转操作:

glRotatef(angle, 0.0, -1.0, 0.0);   
glTranslatef(2.0, 0.0, 0.0);


解释:

翻译:见glTranslate的文档:

glTranslate produces a translation by x y z . The current matrix (see glMatrixMode) is multiplied by this translation matrix, with the product replacing the current matrix.

旋转:参见glRotate的文档:

glRotate produces a rotation of angle degrees around the vector x y z . The current matrix (see glMatrixMode) is multiplied by a rotation matrix with the product replacing the current matrix.


翻译矩阵如下所示:

Matrix4x4 translate;

translate[0] : ( 1,  0,  0,  0 )
translate[1] : ( 0,  1,  0,  0 )
translate[2] : ( 0,  0,  1,  0 )
translate[3] : ( tx, ty, tz, 1 )

绕 Y 轴的旋转矩阵如下所示:

Matrix4x4  rotate;
float      angle;

rotate[0] : ( cos(angle),  0, sin(angle), 0 )
rotate[1] : ( 0,           1, 0,          0 )
rotate[2] : ( -sin(angle), 0, cos(angle), 0 )
rotate[3] : ( 0,           0, 0,          1 )   


translate * rotate 的结果是这样的:

model[0] : ( cos(angle),  0,  sin(angle), 0 )
model[1] : ( 0,           1,  0,          0 )
model[2] : ( -sin(angle), 0,  cos(angle), 0 )
model[3] : ( tx,          ty, tz,         1 )


rotate * translate的结果是:

model[0] : ( cos(angle),                     0,   sin(angle),                     0 )
model[1] : ( 0,                              1,   0,                              0 )
model[2] : ( -sin(angle),                    0,   cos(angle),                     0 )
model[3] : ( cos(angle)*tx - sin(angle)*tx,  ty,  sin(angle)*tz + cos(angle)*tz,  1 )