【问题标题】:OpenGL rectangle animationOpenGL矩形动画
【发布时间】:2015-01-20 19:29:54
【问题描述】:

我正在尝试根据随机数输入“动画”矩形的高度。所以对于每个新的随机数,矩形都会重新绘制。

我该怎么做?

我的代码:

#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;
}

虽然程序不会崩溃,但只是简单地绘制了一个矩形。

【问题讨论】:

    标签: c linux opengl obsolete


    【解决方案1】:

    鉴于您的尺寸在0.0 &lt;= dimension &lt;= 1.0 范围内,并且您计算的高度在0 &lt;= height &lt;= 9 范围内,您需要像这样缩放随机数:

    height = (float)rand() / RAND_MAX;
    

    另外请将srand(time(NULL));renderFunction() 移动到main() 否则您的矩形大小将在每一秒内被固定。

    【讨论】:

      【解决方案2】:

      rand()%10 返回一个通常大于或等于 1 的整数。因此高度大多为 1,因为它可以在屏幕上呈现的最大高度为 1。

      【讨论】:

        猜你喜欢
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        • 2016-12-03
        • 1970-01-01
        • 1970-01-01
        • 2018-08-18
        • 2016-09-29
        • 2015-01-15
        相关资源
        最近更新 更多