现在我已经有了立方体,接下来要做的是为每个立方体添加一个随机颜色,但是我在每个立方体上都做这个颜色时遇到了麻烦。正如您在我的代码输出中看到的,立方体的每个面都有相同的颜色,而边是不同的。我在代码中尝试了不同的方法,但是有时立方体的颜色都是相同的。
我想让这些立方体有不同的颜色。
我所需的输出:
下面是代码:
import pygame
import random
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
verticies = ((0.5, -0.5, -0.5), (0.5, 0.5, -0.5), (-0.5, 0.5, -0.5), (-0.5, -0.5, -0.5),
(0.5, -0.5, 0.5), (0.5, 0.5, 0.5), (-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5))
edges = ((0,1), (0,3), (0,4), (2,1),(2,3), (2,7), (6,3), (6,4),(6,7), (5,1), (5,4), (5,7))
surfaces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6)
)
colors = (
(1,0,0),
(0,1,0),
(0,0,1),
(0,1,0),
(1,1,1),
(0,1,1),
(1,0,0),
(0,1,0),
(0,0,1),
(1,0,0),
(1,1,1),
(0,1,1),
)
def Cube():
glBegin(GL_QUADS)
x = 0
for surface in surfaces:
x+=1
for vertex in surface:
glColor3fv(colors[x])
glVertex3fv(verticies[vertex])
glEnd()
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def main():
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
glMatrixMode(GL_PROJECTION)
gluPerspective(60, (display[0]/display[1]), 0.1, 500)
button_down = False
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_MODELVIEW)
modelMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
glTranslatef(0.0,0.0, -5)
while True:
glPushMatrix()
glLoadIdentity()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
glTranslatef(-1, 0, 0)
if event.key == pygame.K_RIGHT:
glTranslatef(1, 0, 0)
if event.key == pygame.K_UP:
glTranslatef(0, 1, 0)
if event.key == pygame.K_DOWN:
glTranslatef(0, -1, 0)
if event.type == pygame.MOUSEMOTION:
if button_down == True:
glRotatef(event.rel[1], 1, 0, 0)
glRotatef(event.rel[0], 0, 1, 0)
for event in pygame.mouse.get_pressed():
if pygame.mouse.get_pressed()[0] == 1:
button_down = True
elif pygame.mouse.get_pressed()[0] == 0:
button_down = False
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glMultMatrixf(modelMatrix)
modelMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
glLoadIdentity()
glTranslatef(0, 0, -5)
glMultMatrixf(modelMatrix)
for i in range(5):
glPushMatrix()
glTranslate(-2+i, 0, 0)
Cube()
glPopMatrix()
glPopMatrix()
pygame.display.flip()
pygame.time.wait(10)
main()
1条答案
按热度按时间bbmckpt71#
定义6种颜色的数组:
不要为每个顶点设置颜色:
但要为每个立方体设置颜色: