在OpenGL中创建带动画点的正弦波?

时间:2014-04-06 10:27:54

标签: c opengl

这是我目前的代码:

void originAxis();
void sineWave();
void idle();


void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

originAxis();
sineWave();

printf("%s\n", gluErrorString(glGetError()));
glutSwapBuffers();
}

void sineWave()
{
float wavelength = 2;
float amplitude = 1;
float inc = 0.05;
float k, x, y;
glBegin(GL_LINES);
    glColor3f(1,1,1);
    for(x=-1;x<=1;x+=inc){
        k = 2 * 3.14 / wavelength;
        y = amplitude * sin(k * x);
        glVertex3f(x, y, 0);
    }
glEnd();

}

void idle()
{
float wavelength = 2;
float amplitude = 1;
float inc = 0.05;
float k, x, y;
for (x = -1; x <= 1; x += inc){
    glBegin(GL_POINTS);
    glPointSize(200);
    glColor3f(0, 1, 0);
    k = 2 * 3.14 / wavelength;
    y = amplitude * sin(k * x);
    glVertex3f(x, y, 0);
    glEnd();
}

glutPostRedisplay();
}

void originAxis()
{
glBegin(GL_LINES);
    glColor3f(1,0,0);
        glVertex3f(0,0,0);
    glVertex3f(1, 0, 0);
    glColor3f(0,1,0);
        glVertex3f(0,0,0);
    glVertex3f(0, 1, 0);
    glColor3f(0,0,1);
        glVertex3f(0,0,0);
    glVertex3f(0, 0, 1);
    glEnd();
}

int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Tutorial 2");

glOrtho(-1, 1, -1, 1, -1, 1);
glEnable(GL_DEPTH_TEST);

glutDisplayFunc(display);
glutIdleFunc(idle);
glutMainLoop();

return EXIT_SUCCESS;
}

这是我的输出:

http://imgur.com/bXct28P.png

问题:

  • 为什么我的正弦波断裂而且不连续?
  • 我也得到零动画,为什么会这样?

1 个答案:

答案 0 :(得分:2)

您的正弦波被破坏是因为GL_LINES在您提供的两个连续点之间绘制一条线,然后在接下来的两个点之间绘制一条线,依此类推。

要绘制连接您提供的所有点的线,请使用GL_LINE_STRIP

还有〜零动画〜因为你每帧画出相同的东西(在这里没有真正明白你的疑问)

以下是我喜欢Google图片中带有基元类型

的图片

http://3dgep.com/wp-content/uploads/2011/02/OpenGL-Primitives.png