如何在OpenGL中为对象的每个面设置单独的颜色?

x33g5p2x  于 2022-11-04  发布在  其他
关注(0)|答案(1)|浏览(158)

总OpenGL菜鸟在这里...我试图颜色的每一面金字塔在不同的颜色,这样:

glBegin(GL_POLYGON)
    f1 = ((1,-1,-1),(1,-1,1),(0,1,0))
    f2 = ((1,-1,1),(-1,-1,1),(0,1,0))
    f3 = ((-1,-1,-1),(-1,-1,1),(0,1,0))
    f4 = ((1,-1,-1),(-1,-1,-1),(0,1,0))
    f5 = ((1,-1,-1),(1,-1,1),(-1,-1,-1),(-1,-1,1))
    for i in f1:
        glColor3f(0,255,255)
        glVertex3fv(i)
    for i in f2:
        glColor3f(255,0,0)
        glVertex3fv(i)
    for i in f3:
        glColor3f(0,255,0)
        glVertex3fv(i)
    for i in f4:
        glColor3f(255,255,0)
        glVertex3fv(i)
    for i in f5:
        glColor3f(255,0,255)
        glVertex3fv(i)
    glEnd()

但是结果很糟糕...我做错了什么?My current pyramid

djp7away

djp7away1#

基本类型GL_POLYGON会在glBegin/glEnd序列中的所有顶点中产生一个大多边形。请注意,OpenGL无法猜测一个多边形由多少个点组成。您需要以单独的glBegin/glEnd序列绘制多边形:

faces = [
    ((1,-1,-1),(1,-1,1),(0,1,0)),
    ((1,-1,1),(-1,-1,1),(0,1,0)),
    ((-1,-1,-1),(-1,-1,1),(0,1,0)),
    ((1,-1,-1),(-1,-1,-1),(0,1,0)),
    ((1,-1,-1),(1,-1,1),(-1,-1,-1),(-1,-1,1))
]
colors = [(0,255,255), (255,0,0), (0,255,0), (255,255,0), (255,0,255)]

for face, color in zip(faces, colors):
    glColor3fv(color)

    glBegin(GL_POLYGON)
    for vertex in face:
        glVertex3fv(vertex)
    glEnd()

或者,您可以绘制GL_TRIANGLES,并使用2个三角形制作金字塔的底部:

tringles = [
    ((1,-1,-1),   (1,-1,1),   (0,1,0)),
    ((1,-1,1),   (-1,-1,1),  (0,1,0)),
    ((-1,-1,-1), (-1,-1,1),  (0,1,0)),
    ((1,-1,-1),  (-1,-1,-1), (0,1,0)),
    ((1,-1,-1),  (1,-1,1),   (-1,-1,-1)),
    ((1,-1,-1),  (-1,-1,-1), (-1,-1,1))
]
colors = [
    (0,255,255), (255,0,0), (0,255,0), (255,255,0), 
    (255,0,255), (255,0,255)
]

glBegin(GL_TRINAGLES)
for tringle, color in zip(tringles, colors):
    glColor3fv(color)
    for vertex in triangle:
        glVertex3fv(vertex)
glEnd()

相关问题