类对象无法正确生成

时间:2015-07-06 16:08:52

标签: c++ opengl glut

当您左键单击时,尝试在鼠标位置的OpenGL中生成一个圆圈,但圆圈会在最近生成的圆圈位置产生(奇怪吗?) 代码(仅用0.1f生成一个圆圈,0.1f不起作用):

void spawn(int btn, int state, int mX, int mY){
if (btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN){
    circles.push_back(Ball());
    circles[count].setBallX(0.1f);
    circles[count].setBallY(0.1f);
    circles[count].appear();
    count++;
}

并显示圈子:

void display() {
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
    for(int i = 0; i<count; i++){
    if(circles[i].getSpawn()){
    physics(i);
    glTranslatef(circles[i].getBallX(), circles[i].getBallY(), 0.0f);
    glBegin(GL_TRIANGLE_FAN);
        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex2f(0.0f, 0.0f);
        int numSegments = 100;
        GLfloat angle;
        for (int j = 0; j <= numSegments; j++) {
            angle = j * 2.0f * PI / numSegments;
            glVertex2f(cos(angle) * circles[i].getBallRadius(), sin(angle) * circles[i].getBallRadius());
        }
    glEnd();
    }
}   
glutSwapBuffers();
}

我在这里做错了什么想法?

1 个答案:

答案 0 :(得分:0)

glLoadIdentity()移到for - 循环中:

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    for(int i = 0; i<count; i++)
    {
        glLoadIdentity();

        if(circles[i].getSpawn())
        {
            physics(i);
            glTranslatef(circles[i].getBallX(), circles[i].getBallY(), 0.0f);
            glBegin(GL_TRIANGLE_FAN);
            glColor3f(0.0f, 0.0f, 1.0f);
            glVertex2f(0.0f, 0.0f);
            int numSegments = 100;
            GLfloat angle;
            for (int j = 0; j <= numSegments; j++)
            {
                angle = j * 2.0f * PI / numSegments;
                glVertex2f(cos(angle) * circles[i].getBallRadius(), sin(angle) * circles[i].getBallRadius());
            }
            glEnd();
        }
    }   
    glutSwapBuffers();
}

或推/弹你的矩阵:

void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    for(int i = 0; i<count; i++)
    {
        if(circles[i].getSpawn())
        {
            physics(i);
            glPushMatrix();
            glTranslatef(circles[i].getBallX(), circles[i].getBallY(), 0.0f);
            glBegin(GL_TRIANGLE_FAN);
            glColor3f(0.0f, 0.0f, 1.0f);
            glVertex2f(0.0f, 0.0f);
            int numSegments = 100;
            GLfloat angle;
            for (int j = 0; j <= numSegments; j++)
            {
                angle = j * 2.0f * PI / numSegments;
                glVertex2f(cos(angle) * circles[i].getBallRadius(), sin(angle) * circles[i].getBallRadius());
            }
            glEnd();
            glPopMatrix();
        }
    }   
    glutSwapBuffers();
}

否则,您将多个glTranslate()堆叠在一起,这可能不是您想要的。