【问题标题】:Internal nested while loop wont execute内部嵌套的while循环不会执行
【发布时间】:2014-02-01 03:53:14
【问题描述】:

我正在尝试创建一个嵌套的 while 循环结构,它将创建一个 3 * 3 的立方体网格。它似乎只运行一次内部循环,用立方体创建一个“L”形。所以,我的猜测是内部 while 循环在第一次运行后并没有重置,但我确实似乎明确地重置了它。

我宁愿不发布整个代码,因为有些是我的 TA 提供的代码,未经他们的许可发布是不对的。

void display()
{
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   glEnable(GL_DEPTH_TEST);

   UpdateTransform();

   int x = 0;
   int y = 0;
   float Xres = 0;
   float Yres = 0;
   while(x < 3)
   {
     glPushMatrix();
     glTranslatef(Xres,0,0);
     drawOneCube();
     glPopMatrix();

     Xres += 0.3;


     while(y < 3)
     {

       glPushMatrix();
       glTranslatef(0,Yres,0);
       drawOneCube();
       glPopMatrix();


       Yres += 0.3;
       y++;
     }

     y = 0;
     Yres = 0;
     x++;
   }

   glutSwapBuffers();//this prevents that problem where the window copies the contents behind the window, possibly with glClear at the top of this function
}

【问题讨论】:

    标签: c++ opengl nested-loops


    【解决方案1】:

    看来您的逻辑不正确。您应该只在某一时刻调用立方体绘制函数,如下所示:

    void display()
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glEnable(GL_DEPTH_TEST);
        UpdateTransform();
    
        int x = 0;
        int y = 0;
        float Xres = 0;
        float Yres = 0;
    
        for (x = 0; x < 3; ++x)
        {
            Yres = 0;
            for (y = 0; y < 3; ++y)
            {
                glPushMatrix();
                glTranslatef(Xres,Yres,0);
                drawOneCube();
                glPopMatrix();
                Yres += 0.3;
            }
            Xres += 0.3;
        }
    
        glutSwapBuffers();
    }
    

    【讨论】:

    • 感谢您的回复,但我仍然得到相同的“L”输出。
    • 它对循环有什么影响?变量y 已设置为零并被重置。 OPs 问题不太可能与循环不执行有关。
    • @mock:要么是他添加的,要么是我错过了。 (由于我的回复,我很确定他添加了它。)
    • (好吧,stackoverflow 很有趣!这是我的第一篇文章,没想到会有这么快的响应!我相信,Chad 刚刚清理了我的代码,添加了缩进以使其更漂亮、更具可读性。我的不好 :D) 但是,仍然试图解决这个问题,for 循环并没有为我解决它,而是尝试了所有建议。
    • 你太棒了,感谢完美。是的,我的逻辑完全有缺陷,但我现在明白为什么了。谢谢! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多