OpenGL随机大小矩形代码更改绘制的矩形

时间:2018-09-16 03:21:44

标签: c++ opengl glut

我想在鼠标单击的位置绘制随机大小的正方形。但是我的代码更改了已经绘制的矩形的大小。我想问一下如何更改我的代码,而不是更改之前绘制的矩形的大小。 这是我的代码。

GLfloat myVertices[10][2];      
GLint count = 0;

std::default_random_engine(dre);
std::uniform_int_distribution<> uid(10, 100);

void Mouse(int button, int state, GLint x, GLint y)
{
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        myVertices[count][0] = x;
        myVertices[count][1] = (600 - y);

        count++;         
    }
}

GLvoid drawScene()                                  
{
    GLint index;
    if (count > 0)
    {
        for (index = 0; index < count; index++)
        {
            glRectf(myVertices[index][0], myVertices[index][1], myVertices[index][0] + uid(dre), myVertices[index][1] + uid(dre));
        }
    }

    glFlush();                              
}

1 个答案:

答案 0 :(得分:1)

每次绘制场景时,您的代码都会生成新的矩形大小。您也必须存储它们。

我会说类似的话。

struct Rect {
    GLfloat x1,y1;
    GLfloat x2,y2;
};

std::vector <Rect> myVertices;

void Mouse(int button, int state, GLint x, GLint y)
{
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        myVertices.emplace_back(x,(600 - y),x + uid(dre), (600 - y) + uid(dre) );   
    }
}

GLvoid drawScene()                                  
{
    GLint index;
    if (count > 0)
    {
        for(auto const& rect: myVertices) 
        {
            glRectf(rect.x1,rect.y1,rect.x2,rect.y2);
        }
    }

    glFlush();                              
}