当显示尺寸改变时,Pygame / pyopengl形状会发生变化

时间:2015-02-21 08:26:10

标签: python python-2.7 pygame pyopengl

我一直在尝试做这里所做的事情: http://pythonprogramming.net/opengl-pyopengl-python-pygame-tutorial/

虽然一切看起来基本相同,但我的立方体看起来像一个矩形棱镜。

将显示尺寸切换为600x600使其成为一个立方体,但我想将其保持在800x600(或者,我想保持对象不受窗口大小的影响而扭曲。)

有没有办法做到这一点(我意识到作者正在使用python3而我正在做python2.7,是问题还是有解决方法)?

这是我的代码

#!/usr/bin/env python
import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

vertices = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
    )

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),
    (1, 0, 0),
    (0, 0, 1),
    (0, 0, 0),
    (1, 1, 1),
    (0, 1, 1),
    (1, 0, 0),
    (1, 0, 0),
    (0, 0, 1),
    (0, 0, 0),
    (1, 1, 1),
    (0, 1, 1),
    )

def Cube():
    glBegin(GL_QUADS)
    for surface in surfaces:
        x = 0
        for vertex in surface:
            x = (x + 1) % 12
            glColor3fv(colors[x])
            glVertex3fv(vertices[vertex])
    glEnd()
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
    glTranslatef(0, 0, -40)
    glRotatef(0, 0, 0, 0)
    loop = True
    while loop:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    glTranslatef(0.5, 0, 0)
                if event.key == pygame.K_RIGHT:
                    glTranslatef(-0.5, 0, 0)
                if event.key == pygame.K_UP:
                    glTranslatef(0, -0.5, 0)
                if event.key == pygame.K_DOWN:
                    glTranslatef(0, 0.5, 0)
                if event.key == pygame.K_SPACE:
                    loop = False
        #glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glTranslatef(0,0,0.1)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)

main()

谢谢!

1 个答案:

答案 0 :(得分:0)

问题的确在于你使用python 2.7,并且有一个简单的解决方法。

在python 3中,默认是浮点:

>>> 800/600
1.3333333333333333

而在python 2.7中它是整数:

>>> 800/600
1

一个简单的解决方法是改变这一行:

gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)

使用

gluPerspective(45, (1.0*display[0]/display[1]), 0.1, 50.0)