1

I'm trying to 'animate' a rectangle's height based on a random number input. So with each new random number, the rectangle is re-drawn.

How do I do this?

My code:

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

While the program doesn't crash is simply draws a single rectangle.

Stephane Gosselin
  • 9,030
  • 5
  • 42
  • 65
ranger3
  • 23
  • 3

2 Answers2

0

The rand()%10 returns an integer which is usually greater than or equal to 1. So the height is mostly 1 since the maximum height it can render on the screen is 1.

0

Given that your sizes are in the range 0.0 <= dimension <= 1.0 and the height you calculate is in the range 0 <= height <= 9, you need to scale the random number like this:

height = (float)rand() / RAND_MAX;

Also please move srand(time(NULL)); from renderFunction() to main() otherwise your rectangle sizes will be clamped during every second.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56