Opengl glRotatef旋转多边形,不会旋转到位

时间:2013-11-05 02:19:11

标签: opengl rotation

我正在尝试将多边形旋转到位,但它会继续旋转。

要旋转,我通过查找每个顶点的平均位置来计算中心。我调用旋转功能,然后使用中心调用翻译将其移动到屏幕中间。它确实以焦点为中心,但它仍然像它不是一样旋转。关于我可能做错什么的任何想法?

这是我的代码:

void Polygon::DrawPolygon()
{
    glPushMatrix();
    glLoadMatrixf(matrix);
    glTranslatef(displace[0], displace[1], displace[2]);
    glRotatef(rotation[0], 1, 0, 0);
    glRotatef(rotation[1], 0, 1, 0);
    glRotatef(rotation[2], 0, 0, 1);
    glTranslatef(-displace[0], -displace[1], displace[2]);
    displace[0] = 0; displace[1] = 0; displace[2] = 0;
    glGetFloatv(GL_MODELVIEW_MATRIX, matrix);
    DrawMaterial();
    DrawFaces();
    ConnectFaces();
    glPopMatrix();
}

以下是我计算中心的方法:

void Polygon::FindCenter()
{
    float x = 0;
    float y = 0;
    float z = 0;

    for(int j = 0; j < 2; j++)
    {
        for(int i =  0; i < vertexCount; i++)
        {
            x += vertices[i][0];
            y += vertices[i][1];
            z += vertices[i][2] + extrusionDistance * j;
        }
    }
    x = x / (vertexCount * 2);
    y = y / (vertexCount * 2);
    z = z / (vertexCount * 2);

    displace[0] = x;
    displace[1] = y;
    displace[2] = z;
}

由于我的挤压工作方式,我不需要为两个面的顶点添加x和y,但我仍然做了以保持它一致。

以下是我绘制形状的方法:

void Polygon::DrawFaces()
{
    for(int j = 0; j < 2; j++)
    {
        glBegin(GL_POLYGON);
        for(int i = 0; i < vertexCount; i++)
        {
             glVertex3f(vertices[i][0], vertices[i][1], j*extrusionDistance);
        }
        glEnd();
    }
}

void Polygon::ConnectFaces()
{
    for(int i = 0; i < vertexCount; i++)
    {
        glBegin(GL_POLYGON);
        glVertex3f(vertices[i][0], vertices[i][1], 0);
        glVertex3f(vertices[i][0], vertices[i][1], extrusionDistance);
        glVertex3f(vertices[(i+1)%vertexCount][0], vertices[(i+1)%vertexCount][1], extrusionDistance);
        glVertex3f(vertices[(i+1)%vertexCount][0], vertices[(i+1)%vertexCount][1], 0);
        glEnd();
    }
}

1 个答案:

答案 0 :(得分:0)

我看到一些让我觉得奇怪的事情:

1)您在致电glLoadMatrixf(matrix)glTranslate()之前致电glRotate()。根据您加载的矩阵中的内容,这会改变一切。

2)您的FindCenter()方法通过在计算z中包含vertex[i][2]来计算中心,但是当您在DrawFaces()中实际绘制面时,则不包括vertex[i][2]部分,只是extrusion * j部分。所以你没有画出你计算中心的东西。