为什么这段代码不起作用?
// 1 square (made by 4 quads) to be rendered
GLfloat vertices_position[] = {
x, y,
x+w, y,
x+w, y+h,
x, y+h,
};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertices_position);
glDrawArrays(GL_QUADS, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
我正在使用glew,我没有编译错误,我得到的一切都没有画在屏幕上。
如果我使用它,它可以正常工作:
glPushMatrix();
glTranslatef(0, 0, 0);
glScalef(scale,scale,1);
//set color
glColor4f(R, G, B, A);
glBegin( GL_QUADS );
glTexCoord2f( texLeft, texTop );
glVertex2f( x, y );
glTexCoord2f( texRight, texTop );
glVertex2f( x+w, y );
glTexCoord2f( texRight, texBottom );
glVertex2f( x+w, y+h );
glTexCoord2f( texLeft, texBottom );
glVertex2f( x, y+h );
glEnd();
glPopMatrix();
答案 0 :(得分:4)
我很蠢...... 我指定使用纹理但从未绑定任何顶点...
这段代码很好用:
GLfloat vertices_position[] = {
x, y,
x+w, y,
x+w, y+h,
x, y+h,
};
GLfloat texture_coord[] = {
texLeft, texTop,
texRight, texTop,
texRight, texBottom,
texLeft, texBottom,
};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertices_position);
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glTexCoordPointer(2, GL_FLOAT, 0, texture_coord);
glDrawArrays(GL_QUADS, 0, 4);
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
glDisableClientState( GL_VERTEX_ARRAY );
答案 1 :(得分:0)
在这里工作得很好:
#include <GL/glew.h>
#include <GL/glut.h>
bool vertexArray = false;
void keyboard( unsigned char key, int x, int y )
{
if( key == 't' ) vertexArray = !vertexArray;
glutPostRedisplay();
}
void display()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double winWidth = glutGet( GLUT_WINDOW_WIDTH );
double winHeight = glutGet( GLUT_WINDOW_HEIGHT );
double ar = winWidth / winHeight;
glOrtho( -1 * ar, 1 * ar, -1, 1, -1, 1);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
float x = -0.5f;
float y = -0.5f;
float w = 1;
float h = 1;
float scale = 1;
glPushMatrix();
glTranslatef(0, 0, 0);
glScalef(scale,scale,1);
//set color
glColor4f( 1, 0, 0, 1 );
if( vertexArray )
{
GLfloat vertices_position[] = {
x, y,
x+w, y,
x+w, y+h,
x, y+h,
};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertices_position);
glDrawArrays(GL_QUADS, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
}
else
{
glBegin( GL_QUADS );
glVertex2f( x, y );
glVertex2f( x+w, y );
glVertex2f( x+w, y+h );
glVertex2f( x, y+h );
glEnd();
}
glPopMatrix();
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 640, 480 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutKeyboardFunc( keyboard );
glewInit();
glutMainLoop();
return 0;
}