0

I need to draw a Polygon iteratively. for example, I want to draw a Polygon with 8 corners. I need to draw the first line with GL_LINES and then draw the second line with the same length and an angle of 135° between them, the third line has also an angle of 135° to the second line, etc. I want to make a loop to render it but I don't know how. I have an approach, but it doesn't work properly.

the second point of line n-1 should be the first point of n and so on... At the end, I need to get a closed Polygon. the last point of the last line should be the first point of the first line.

4

1 回答 1

2

使用GL_LINE_LOOP,它将自动将您的最后一个顶点连接到您的第一个顶点:

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

void glPolygon( unsigned int sides )
{
    if( sides < 3 ) return;

    const float PI = 3.14159;
    const float step = ( 2 * PI ) / static_cast< float >( sides );

    glBegin( GL_LINE_LOOP );
    for( unsigned int i = 0; i < sides; ++i )
    {
        glVertex2f( cos( i * step ), sin( i * step ) );
    }
    glEnd();
}

void display()
{
    glClear( GL_COLOR_BUFFER_BIT );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double ar = glutGet( GLUT_WINDOW_WIDTH ) / (double)glutGet( GLUT_WINDOW_HEIGHT );
    glOrtho( -2 * ar, 2 * ar, -2, 2, -1, 1);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glColor3ub( 255, 0, 0 );
    glPolygon( 8 );

    glutSwapBuffers();
}

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

GL_LINES如果你对这个作品死心塌地:

void glPolygonLines( unsigned int sides )
{
    if( sides < 3 ) return;

    const float PI = 3.14159f;
    const float step = ( 2 * PI ) / static_cast< float >( sides );

    glBegin( GL_LINES );
    for( unsigned int i = 0; i < sides; ++i )
    {
        unsigned int cur = ( i + 0 ) % sides;
        unsigned int nxt = ( i + 1 ) % sides;
        glVertex2f( cos( cur * step ), sin( cur * step ) );
        glVertex2f( cos( nxt * step ), sin( nxt * step ) );
    }
    glEnd();
}
于 2012-10-31T13:52:31.477 回答