2015-01-20 89 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