我想用openGL在屏幕上繪製100個點。這意味着每次運行程序時,屏幕上都會隨機顯示100個GL_POINTS。目前屏幕上只剩下一個點,並且它的位置是以前給出的。但是,我的隨機點只出現一段時間,然後消失。我不知道我錯過了什麼才能使它工作。以下是我的代碼openGL中的隨機點生成
#include <stdlib.h>
#include <GL/freeglut.h>
#include <math.h>
GLfloat cameraPosition[] = { 0.0, 0.2, 1.0 };
/* Random Star position */
GLfloat starX, starY, starZ;
GLint starNum = 0;
void myIdle(void){
starNum += 1;
/* Generate random number between 1 and 4. */
starX = 1.0 + static_cast <float> (rand())/(static_cast <float> (RAND_MAX/3.0));
starY = 1.0 + static_cast <float> (rand())/(static_cast <float> (RAND_MAX/3.0));
starZ = 1.0 + static_cast <float> (rand())/(static_cast <float> (RAND_MAX/3.0));
/* Now force OpenGL to redraw the change */
glutPostRedisplay();
}
// Draw a single point
void stars(GLfloat x, GLfloat y, GLfloat z){
glBegin(GL_POINTS);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(x, y, z);
glEnd();
}
// Draw random points.
void myDisplay(void){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLoadIdentity();
gluLookAt(cameraPosition[0], cameraPosition[1], cameraPosition[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
/* They show up on the screen randomly but they disappear after starNum greater than 100 */
if (starNum < 100){
glPushMatrix();
stars(starX, starY, starZ);
glPopMatrix();
}
/* This point will remain on the screen. */
glPushMatrix();
stars(2.0, 2.0, 2.0);
glPopMatrix();
/* swap the drawing buffers */
glutSwapBuffers();
}
void initializeGL(void){
glEnable(GL_DEPTH_TEST);
glClearColor(0, 0, 0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glPointSize(2.0);
glOrtho(-4.0, 4.0, -4.0, 4.0, 0.1, 10.0);
glMatrixMode(GL_MODELVIEW);
}
void main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(1800, 1000);
glutInitWindowPosition(100, 150);
glutCreateWindow("Random points");
/* Register display function */
glutDisplayFunc(myDisplay);
/* Register the animation function */
glutIdleFunc(myIdle);
initializeGL();
glutMainLoop();
}
任何想法我錯過了什麼?
你期望什麼?如果'starNum <100',你正在畫星星,並想知道爲什麼當這種情況不再被滿足時他們消失了?我不明白你的意外。 –
我想在屏幕上畫出100點,並且它們的位置是隨機的。基本上,我希望所有的星星都留在屏幕上。 – zihaow
OpenGL不是場景圖形API。每次調用顯示功能時,都需要繪製所有星星。 –