OpenGL画一颗星

时间:2018-07-23 04:49:37

标签: java opengl

我是学习OpenGL的新手,目前正在研究2D星。我能够为这些点创建5个三角形,然后为中间创建多边形,但是当我运行该程序时,该多边形会切出一部分未着色的部分。我试图用三角形覆盖未覆盖的部分,但这也没有用。如果有人对代码有什么问题有什么想法,或者可以添加什么以确保我的形状没有缺失的颜色,我将不胜感激。

这是我的代码:

void draw() {


    glBegin(GL_TRIANGLES);

    glColor3f(1, 0, 0);
    glVertex3f(-0.60, 0.77, 0);

    glColor3f(0, 1, 0);
    glVertex3f(-0.42, 0.77, 0);

    glColor3f(0, 0, 1);
    glVertex3f(-0.58, 0.68, 0);

    //second triangle top triangle

    glColor3f(1, 0, 0);
    glVertex3f(-0.64, 1, 0);

    glColor3f(0, 1, 0);
    glVertex3f(-0.68, 0.77, 0);

    glColor3f(0, 0, 1);
    glVertex3f(-0.60, 0.77, 0);

    //3rd Triangle
    glColor3f(1, 0, 0);
    glVertex3f(-0.68, 0.77, 0);

    glColor3f(0, 1, 0);
    glVertex3f(-0.7, 0.68, 0);

    glColor3f(0, 0, 1);
    glVertex3f(-0.86, 0.77, 0);

    //4th Triangle
    glColor3f(1, 0, 0);
    glVertex3f(-0.64, 0.63, 0);

    glColor3f(0, 1, 0);
    glVertex3f(-0.7, 0.68, 0);

    glColor3f(0, 0, 1);
    glVertex3f(-0.82, 0.43, 0);

    //5th Triangle
    glColor3f(1, 0, 0);
    glVertex3f(-0.64, 0.63, 0);

    glColor3f(0, 1, 0);
    glVertex3f(-0.58, 0.68, 0);

    glColor3f(0, 0, 1);
    glVertex3f(-0.51, 0.43, 0);

    glEnd();

    glBegin(GL_POLYGON);//code for the Polygon within the stars
    glColor3f(1, 0, 0);//sets color of Polygon

    glVertex3f(-0.68, 0.77, 0); //set the 5 vetices of polygon

    glColor3f(1, 0, 0);
    glVertex3f(-0.60, 0.77, 0);

    glColor3f(1, 0,0 );
    glVertex3f(-0.7, 0.68, 0);

    glColor3f(1, 0, 0);
    glVertex3f(-0.64, 0.63, 0);

    glColor3f(1, 0, 0);
    glVertex3f(-0.58, 0.68, 0);




    glEnd();

    //code for pentagaon
    glBegin(GL_POLYGON);
    glColor3f(1, 0, 0);//sets color of Polygon
    glVertex3f(0.45, 0.82, 0); //set the 5 vetices of polygon

    glColor3f(0, 1, 0);
    glVertex3f(0.8, 0.6, 0);

    glColor3f(0, 1, 0);
    glVertex3f(0.2, 0.6, 0);

    glColor3f(1, 0, 0);
    glVertex3f(0.2, 0.3, 0);

    glColor3f(1, 0, 0);
    glVertex3f(0.7, 0.3, 0);


    glEnd();
}

1 个答案:

答案 0 :(得分:0)

首先要注意的是,由glBegin / glEnd序列绘制而成的原始类型GL_POLYGON已被弃用了10多年了。 阅读Fixed Function Pipeline并参阅Vertex Specification了解最新的渲染方式。


您交换了多边形的前2个顶点坐标的x坐标。像这样更改代码,以解决问题:

glColor3f(1, 0, 0);
glBegin(GL_POLYGON);

glVertex3f(-0.60, 0.77, 0); // <--- -0.60 instead of -0.68
glVertex3f(-0.68, 0.77, 0); // <--- -0.68 instead of -0.60
glVertex3f(-0.7, 0.68, 0);
glVertex3f(-0.64, 0.63, 0);
glVertex3f(-0.58, 0.68, 0);

glEnd();

请注意,可以使用GL_TRIANGLE_FAN代替不推荐使用的原始类型GL_POLYGON