2013-10-15 116 views
2

Image of a sine wave drawn over 2PI with red dots 我應該使用OpenGL_POINTS繪製一個正弦波(如圖中的那個)。但是,在通過代碼中的循環之後,我不斷獲得一個wave的一個點。如何使用C++在OpenGL_POINTS函數中繪製正弦波

這是我的代碼。

#include "stdafx.h" 
#include <iostream> 
#include <gl\GLUT.h> 
#include <math.h> 

using namespace std; 

void RenderSineWave() 
{ 
    int i; 
float x,y; 
glClearColor(0.0, 0.0, 0.0, 1.0); // clear background with black 
glClear(GL_COLOR_BUFFER_BIT); 

    glPointSize(10); 
    glColor3f(1.0,0.0,0.0); 


     for(i=0;i<361;i=i+5) 
     { 

      x = (float)i; 
      y = 100.0 * sin(i *(6.284/360.0)); 
      glBegin(GL_POINTS); 
      glVertex2f(x,y); 
      glEnd(); 
     glFlush(); 
     glutPostRedisplay(); 
     } 

} 

void main(int argc, char** argv) 
{ 
    glutInit(&argc,argv); 
    glutCreateWindow("SineWave.cpp"); 
glutDisplayFunc(RenderSineWave); 
glutMainLoop(); 

} 
+0

不要打電話glutpostredisplay每次渲染點,告訴我,如果說工作 –

回答

4

glutMainLoop();前加入這一行告訴OpenGL在x-1365之間繪製,並在y-200200(默認值是太小,看整體的形狀)之間:

gluOrtho2D(-1,365,-200,200); 

此外,刪除行glutPostRedisplay();,否則您的屏幕可能會閃爍。

+0

感謝memo1288和其他人的幫忙。投影矩陣做到了。 – user2875230

6

嘗試設置一個合理的投影矩陣:

#include <GL/glut.h> 
#include <cmath> 

using namespace std; 

void RenderSineWave() 
{ 
    glClearColor(0.0, 0.0, 0.0, 1.0); // clear background with black 
    glClear(GL_COLOR_BUFFER_BIT); 

    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    double w = glutGet(GLUT_WINDOW_WIDTH); 
    double h = glutGet(GLUT_WINDOW_HEIGHT); 
    double ar = w/h; 
    glOrtho(-360 * ar, 360 * ar, -120, 120, -1, 1); 

    glMatrixMode(GL_MODELVIEW); 
    glLoadIdentity(); 

    glPointSize(10); 
    glColor3f(1.0,0.0,0.0); 

    glBegin(GL_POINTS); 
    for(int i=0;i<361;i=i+5) 
    { 
     float x = (float)i; 
     float y = 100.0 * sin(i *(6.284/360.0)); 
     glVertex2f(x,y); 
    } 
    glEnd(); 

    glutSwapBuffers(); 
} 

int main(int argc, char** argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); 
    glutInitWindowSize(640, 480); 
    glutCreateWindow("SineWave.cpp"); 
    glutDisplayFunc(RenderSineWave); 
    glutMainLoop(); 
    return 0; 
}