2015-01-20 93 views
1

我正在嘗試基於隨機數字輸入'設置矩形的高度'。因此,隨着每個新的隨機數,該矩形被重新繪製。OpenGL矩形動畫

我該怎麼做?

我的代碼:

#include <time.h> 
#include <GL/freeglut.h> 
#include <GL/gl.h> 

float height; 
int i; 

/* display function - code from: 
    http://fly.cc.fer.hr/~unreal/theredbook/chapter01.html 
This is the actual usage of the OpenGL library. 
The following code is the same for any platform */ 
void renderFunction() 
{ 
    srand(time(NULL)); 
    height = rand() % 10; 

    glClearColor(0.0, 0.0, 0.0, 0.0); 
    glClear(GL_COLOR_BUFFER_BIT); 
    glColor3f(0.0, 0.0, 1.0); 
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); 
    glBegin(GL_POLYGON); 
     glVertex2f(-0.5, -0.5);  // bottom left corner 
     glVertex2f(-0.5, height);  // top left corner 
     glVertex2f(-0.3, height);  // top right corner 
     glVertex2f(-0.3, -0.5);  // bottom right corner 
    glEnd(); 
    glFlush(); 
} 

/* Main method - main entry point of application 
the freeglut library does the window creation work for us, 
regardless of the platform. */ 
int main(int argc, char** argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_SINGLE); 
    glutInitWindowSize(900,600); 
    glutInitWindowPosition(100,100); 
    glutCreateWindow("OpenGL - First window demo"); 

    glutDisplayFunc(renderFunction); 
    glutIdleFunc(renderFunction); 
    glutReshapeFunc(renderFunction); 

    glutMainLoop(); 

    return 0; 
} 

當程序不崩潰僅僅是繪製一個矩形。

回答

0

鑑於你的尺寸範圍0.0 <= dimension <= 1.0和你計算的高度範圍內0 <= height <= 9,您需要縮放的隨機數是這樣的:

height = (float)rand()/RAND_MAX; 

也請從renderFunction()main()否則你的矩形大小將在每一個本身被夾住移動srand(time(NULL));條件。

0

rand()%10返回一個整數,它通常是大於或等於1,所以高度大多是1,因爲它可以在屏幕上呈現的最大高度爲1