JonAmen JonAmen - 2 months ago 10
C++ Question

How to draw a moving function graph with OpenGl?

I'm using OpenGl to animate a graph that looks something like this:
enter image description here

Here's the code I've got so far:

void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0,1,0); //Green

// Frequency Line
glLineWidth(3.0);
glBegin(GL_LINE_STRIP);
glVertex2f(-1,0);
glVertex2f(x1,y1);
glEnd();
y1 = randVarGen();
x1 = randVarGen();


and I have a timer to redraw the graph every 50 ms. I want to start with a straight line and based on variables from an audio file(I'm using random variables for now), the graph should go up and down sort of like a music visualizer.

Answer

You need to sample the function you want to plot.

glBegin(GL_LINE_STRIP);
glVertex2f(0f, 0f);
for (float x = 1f; x < 100f; x += 1f)
  glVertex2f(x, randVarGen());
glVertex2f(100f, 0f);
glEnd();
Comments