0

我有这个小程序应该在 2D 中旋转一个正方形。当我给它固定的顶点时,它工作正常。但是当我试图让它运动时,正方形开始闪烁和闪烁,根本不像一个正方形。一切对我来说都很好,所以我一定是错过了什么。任何人都可以看到吗?

#include <stdio.h>
#include <math.h>
#include <glut/glut.h>

#define DEG_TO_RAD 0.017453

GLsizei ww, wh;
GLfloat theta;

void display()
{
    //clear window
    glClear(GL_COLOR_BUFFER_BIT);

    //draw unit square polygon
    glBegin(GL_POLYGON);
    glVertex2f(sin(DEG_TO_RAD*theta), cos(DEG_TO_RAD*theta));
    glVertex2f(-sin(DEG_TO_RAD*theta), cos(DEG_TO_RAD*theta));
    glVertex2f(-sin(DEG_TO_RAD*theta), -cos(DEG_TO_RAD*theta));
    glVertex2f(sin(DEG_TO_RAD*theta), -cos(DEG_TO_RAD*theta));
//    glVertex2f(-0.5, -0.5);
//    glVertex2f(-0.5, 0.5);
//    glVertex2f(0.5, 0.5);
//    glVertex2f(0.5, -0.5);

    glEnd();

    //flush gl buffers
    glFlush();
}

void init() {
    //set color to black
    glClearColor(0.0, 0.0, 0.0, 0.0);

    //set fill color to white
    glColor3f(1.0, 1.0, 1.0);

    //set up standard orthogonal view with clipping
    //box as cube of side2 centered at origin
    //this is default view and these statements could be removed
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
}

void myreshape(GLsizei w, GLsizei h) {
    //adjust clipping window
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (w<=h)
        gluOrtho2D(-2.0, 2.0, -2.0 * (GLfloat) h / (GLfloat) w, 2.0 * (GLfloat) h / (GLfloat) w);
    else
        gluOrtho2D(-2.0 * (GLfloat) w / (GLfloat) h, 2.0 * (GLfloat) w / (GLfloat) h, -2.0, 2.0);

    glMatrixMode(GL_MODELVIEW);
    //adjust viewport
    glViewport(0, 0, w, h);

    //set global size for use by drawing routine
    ww = w;
    wh = h;
}

void myidle() {
    theta += 2.0;
    if (theta > 360.0) theta -= 360.0;
    glutPostRedisplay();
}

int main(int argc, char** argv)
{
    theta = 0.0;
    // initialize mode and open a window in upper-left corner of screen
    // window title is name of program (arg[0])
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);//Set the window size
    glutInitWindowPosition(0, 0);
    glutCreateWindow("rotating square");
    glutDisplayFunc(display);
    init();
    glutReshapeFunc(myreshape);
    glutIdleFunc(myidle);
    glutMainLoop();
    return 0;
}
4

2 回答 2

2

您的顶点定义不会产生正方形。尝试以下操作:

glVertex2f(cos(DEG_TO_RAD*(theta + 135)), sin(DEG_TO_RAD*(theta + 135)));
glVertex2f(cos(DEG_TO_RAD*(theta + 45 )), sin(DEG_TO_RAD*(theta + 45 )));
glVertex2f(cos(DEG_TO_RAD*(theta - 45 )), sin(DEG_TO_RAD*(theta - 45 )));
glVertex2f(cos(DEG_TO_RAD*(theta - 135)), sin(DEG_TO_RAD*(theta - 135)));
于 2013-09-15T21:15:48.630 回答
0

Andon 在您的问题下方的评论是正确的。您应该只创建一次几何体(顶点),然后通过将矩阵设置为 ModelView 并使用 glRotatef(...) 旋转它们来旋转它们。在每个渲染周期重新创建几何图形是一种错误的方法。

于 2013-09-15T21:17:49.233 回答